我知道这个问题已被问过几次,但不幸的是我无法找到符合我的限制的答案。
我有一个 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/