如何获取进程状态(运行中,被杀死)事件?

时间:2018-08-07 01:47:37

标签: c++ linux events process status

如何获取其他进程的状态?

我想知道另一个进程的执行状态。

我想接收事件并将其处理为inotify。

没有按句号搜索/ proc。

如何使另一个进程状态(运行中,被杀死)事件?

系统:linux,solaris,aix

1 个答案:

答案 0 :(得分:1)

Linux

在Linux(可能还有许多Unixes系统)下,您可以使用ptrace调用,然后使用waitpid等待状态来实现此目的:

联机帮助页:

从联机帮助页:

  

ptrace下的死亡         当(可能是多线程的)进程收到终止信号时         (将其处置设置为SIG_DFL且其默认操作为         (杀死进程),所有线程退出。痕迹报告他们的死亡         给他们的示踪剂。该事件的通知通过         waitpid(2)。

请注意,在某些情况下,您将需要特殊的授权。看一下/proc/sys/kernel/yama/ptrace_scope。 (如果您可以修改目标程序,则还可以通过调用ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);

来更改ptrace的行为。

要使用ptrace,首先必须获取进程PID,然后调用PTRACE_ATTACH

// error checking removed for the sake of clarity
#include <sys/ptrace.h>

pid_t child_pid;

// ... Get your child_pid somehow ...

// 1. attach to your process:

long err; 
err = ptrace(PTRACE_ATTACH, child_pid, nullptr, nullptr);


// 2. wait for your process to stop:
int process_status;

err = waitpid(child_pid, &process_status, 0);

// 3. restart the process (continue)
ptrace(PTRACE_CONT, child_pid, nullptr, nullptr);

// 4. wait for any change in status:

err = waitpid(child_pid, &process_status, 0);
// while waiting, the process is running... 
// by default waitpid will wait for process to terminate, but you can
// change this with WNOHANG in the options.

if (WIFEXITED(status)) {
   // exitted
} 

if (WIFSIGNALED(status)) {
    // process got a signal
    // WTERMSIG(status) will get you the signal that was sent.
}

AIX:

该解决方案需要一些调整才能与AIX一起使用,请看那里的文档:

Solaris

如所提到的here ptrace在您的Solaris版本上可能不可用,您可能必须在该处使用procfs。

相关问题