我想知道在我的程序中是否存在具有特定 ID 的进程。我实现了以下功能来实现这一点,它检查是否 /proc/<PID>/maps
存在。但是,我注意到即使我终止了具有给定 ID 的函数,该函数仍会返回 1。是否有更好的方法来实现我正在尝试做的事情,如果没有,此代码有什么问题(如果有),为什么它应该返回 0 时返回 1 吗?
int proc_exists(pid_t pid)
{
stringstream ss (stringstream::out);
ss << dec << pid;
string path = "/proc/" + ss.str() + "/maps";
ifstream fp( path.c_str() );
if ( !fp )
return 0;
return 1;
}
最佳答案
将kill()
与信号0
一起使用:
if (0 == kill(pid, 0))
{
// Process exists.
}
来自 man kill
:
If sig is 0, then no signal is sent, but error checking is still performed; this can be used to check for the existence of a process ID or process group ID.
关于c++ - 根据进程 ID 确定进程是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12601759/