c++ - 从c/cpp程序中的进程ID获取进程名称(我不能使用/proc/<pid>/cmdline)

标签 c++ c linux pid

我知道这个问题已被问过几次,但不幸的是我无法找到符合我的限制的答案。

我有一个 PID(不是我的进程),我想找到它的名称。现在,我无法访问 /proc/<pid>/cmdline (限制),我找不到获取 ps 输出的方法在我的程序中,除了将其输出发送到文件然后解析它(我需要避免)。

还有其他选择吗?

我正在 Linux/Android 用户空间中使用 C/C++ 进行编码

最佳答案

听起来像ps确实工作(?),但你不能写入临时文件。 (为什么?也许 AppArmor 只限制对某些进程的访问?)

如果这是真的,那么您可以使用管道将 ps 输出直接读取到您的程序中,而无需临时文件。

int fds[2];
pipe(fds);

int pid = fork();
if (pid == 0) {
  // child
  close(fds[0]);  // close the read end of the pipe in the child
  dup2(1,fds[1]); // move the write end to be stdout
  close(fds[1]);

  execlp("ps", "ps", "-p", "blah", NULL);
} else {
  // parent
  close(fds[1]);  // close the write end of the pipe in the parent.

  // read data from fds[0] here

  close(fds[0]);
  int status;
  wait(&status); // clean up the zombie ps process
}

该示例省略了所有错误检查(您必须添加),并且可能不允许(取决于您的访问限制的性质)。

关于c++ - 从c/cpp程序中的进程ID获取进程名称(我不能使用/proc/<pid>/cmdline),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24865395/

相关文章:

C++多索引图实现

c++ - Qt中有没有办法禁止计算机进入休眠状态?

c++ - 将派生类传递给基函数

C初学者题: Pointer arithmetic > cleaning up once you are done

c - 带有 pthread 函数的静态存储

c - 如何在当前语言环境下使用 strerror_l?

c++ - 为什么这个看起来无效的代码在 g++ 6.0 上编译成功?

c++ - 在代码内部、if 语句中使用#import

c - 为什么在尝试 rmmod 时出现 "rmmod: delete_module '/my_module' failed (errno 2)?

linux - Tomcat maxSavePostSize 值?