【问题标题】:how to get process status ( running , killed ) event?如何获取进程状态(运行、终止)事件?
【发布时间】:2018-08-07 01:47:37
【问题描述】:

如何获取另一个进程的状态?

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

我想将事件作为 inotify 接收和处理。

不按句点搜索 /proc。

如何处理另一个进程状态(running,killed)事件?

系统:linux、solaris、aix

【问题讨论】:

标签: c++ linux events process status


【解决方案1】:

Linux

在 Linux(可能还有许多 Unix 系统)下,您可以通过使用 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。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多