我修改了 fork() C 模板来在子进程中执行 ps -l ,我应该查看 ps 行并找到它自己的进程(以查看它与启动之前的子进程的 id 相同)附言)。我在 Ubuntu 上写了这个,它运行得很好,但现在我在 MacOS 上启动了它,我无法在它自己的列表中找到 ps 行。知道为什么它的行为不同吗? 谢谢!
这是C中的代码:
#include <stdio.h> /* Pour perror */
#include <stdlib.h> /* Pour exit */
#include <unistd.h> /* Pour fork, getpid, getppid, sleep */
#include <sys/types.h> /* Pour pid_t (fork, getpid, getppid) */
#include <sys/wait.h> /* Pour wait */
int main(void)
{
pid_t ident;
ident = fork();
if (ident == -1)
{
perror("fork");
return EXIT_FAILURE;
}
/* A partir de cette ligne, il y deux processus */
printf("Cette ligne sera affichee deux fois\n");
if (ident == 0)
{
/* Code execute uniquement par le fils */
printf("Je suis le fils, PID: %d, père: %d\n", getpid(), getppid());
execlp("ps", "ps", "-l", NULL);
}
else
{
/* Code execute uniquement par le pere */
printf("Je suis le pere\n, PID: %d, père: %d\n", getpid(), getppid());
wait(NULL);
}
return EXIT_SUCCESS;
}
默认情况下,macOS 上的
ps
会列出您的进程而不控制终端。 ps
是一个特权命令,在其可执行文件上设置了 sticky 位,并以 root 身份运行。添加 -a
开关来显示其他用户的进程,将显示 ps
进程。