当前位置: 首页 > news >正文

linux中如何获取其他进程的退出状态

进程的退出状态至关重要,用wait系列函数,父进程可以捕捉到子进程的退出状态,若给定任意进程,其父进程已经确定,无法改变,自己如何获取到其退出状态呢。
可以用ptrace系统api attach到相应的进程,然后执行wait就可以在进程退出的时候,捕获其退出状态,代码如下:

#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <errno.h>

int main(int argc, char *argv[])
{
    pid_t pid;

    printf("请输入进程号:\n");
    scanf("%d", &pid);

    printf("子进程暂停 2s\n");
    ptrace(PTRACE_ATTACH, pid, NULL, NULL);
    sleep(2);

    printf("子进程继续执行 5s\n");
    ptrace(PTRACE_CONT, pid, NULL, NULL);

    int wstatus = 0;
    int ret = waitpid(pid, &wstatus, 0);

    if(ret < 0){
        printf("waitpid failed, errno is %d, err msg is %s\n", errno, strerror(errno));
        return ret;
    }

    if (WIFEXITED(wstatus)) {
        int exit_status = WEXITSTATUS(wstatus);
        printf("normal exit, status is %d\n", exit_status);
    }

    return 0;
}
http://www.dtcms.com/a/94644.html

相关文章:

  • 交通数据集
  • leetcode日常刷题
  • 如何对AI玩家进行改进
  • QT错误集合
  • 人工智能与网络安全
  • 动态内存分配与内存对齐
  • MySQL 的 JSON 查询
  • Python 实现机器学习小项目实战教程*
  • 设计模式-结构型模式-外观模式
  • 第十五届蓝桥杯PythonB组
  • Node.js 批量修改文件名脚本
  • 华为OD机试A卷 - 密室逃生游戏(C++ Java JavaScript Python )
  • MQ 如何保证数据一致性?
  • Linux下的socket演示程序2
  • 【Linux网络(七)】数据链路层
  • MySQL 表 t1 建立联合索引 (a, b, c),在 where a < ? and b > ? and c < ? 中哪些索引生效
  • 一台电脑最多能接几个硬盘?
  • localhost 和 127.0.0.1 的区别
  • 图解AUTOSAR_SWS_FlashDriver
  • 5G核心网(5GC)开户中,DNN(Data Network Name,数据网络名称)
  • 【目标检测】【深度学习】【Pytorch版本】YOLOV1模型算法详解
  • Python 爬虫案例
  • Redis:String 类型 内部实现、编码、命令及应用场景
  • Java基础 3.27
  • C语言学习关键笔记
  • DeepSeek详解:探索下一代语言模型
  • 并查集(Union-Find Set)课程笔记
  • 【JavaScript】闭包笔记
  • Ubuntu 防火墙配置
  • 头条项目的文章延迟发布功能