c++ - 根据进程 ID 确定进程是否存在

标签 c++ linux gcc

我想知道在我的程序中是否存在具有特定 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/

相关文章:

c++ - 为什么 gcc 与 clang 相比会产生这种奇怪的程序集?

c++ - 使用 gcc 的别名模板替换和推断失败

c++ - 交换两个序列的元素,使得元素和的差异最小。

c++ - 如何使字符串小写(最简单的方法)? (C++)

python - 尝试在子进程中调用 bash 脚本时,我被拒绝了权限

linux - 解压缩之前 tar 存档中列出的备份文件以进行简单回滚

linux - CMake:使用 MinGW 交叉编译 linux-to-windows 没有找到一些系统头文件

c++ - Fl_Window 子类不起作用

c++ - 模板构造函数没有匹配的函数调用错误

python libcloud 在 vAPP 中创建虚拟机