gpt4 book ai didi

c++ - 如何获取进程状态(正在运行、已终止)事件?

转载 作者:太空宇宙 更新时间:2023-11-04 04:54:10 27 4
gpt4 key购买 nike

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

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

我想作为 inotify 接收并处理该事件。

不按句点搜索/proc。

如何获取另一个进程状态(正在运行、已终止)事件?

系统:linux、solaris、aix

最佳答案

Linux

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

联机帮助页:

来自联机帮助页:

Death under ptrace When a (possibly multithreaded) process receives a killing signal (one whose disposition is set to SIG_DFL and whose default action is to kill the process), all threads exit. Tracees report their death to their tracer(s). Notification of this event is delivered via 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。

关于c++ - 如何获取进程状态(正在运行、已终止)事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51717717/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com