C shell中用于打印进程ID的Fork命令
运行C shell中用于打印进程ID的Fork命令,c,shell,unix,fork,process-reaper,C,Shell,Unix,Fork,Process Reaper,运行fork()命令后,我试图打印进程的pid。这是我的密码- #include <stdio.h> #include <unistd.h> int main(void) { int pid; pid=fork(); if(pid==0) printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid()); else
fork()
命令后,我试图打印进程的pid
。这是我的密码-
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int pid;
pid=fork();
if(pid==0)
printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
else
printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
return 0;
}
为什么第2行中的家长id不是
2420
。为什么我得到1910
我如何得到这个值?在孩子执行printf
调用之前,家长正在退出。当父级退出时,子级将获得一个新的父级。默认情况下,这是init
过程,PID 1。但是Unix的最新版本增加了进程声明自己为“subreaper”的能力,它继承了所有孤儿。PID 1910显然是你系统上的地下机器人。有关此操作的更多信息,请参阅
在父进程中放置一个wait()
调用,使其等待子进程退出,然后再继续
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int pid;
pid=fork();
if(pid==0) {
printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
} else {
printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
wait(NULL);
}
return 0;
}
#包括
#包括
内部主(空)
{
int-pid;
pid=fork();
如果(pid==0){
printf(“我是孩子。我的pid是%d。我的父母pid是%d\n”,getpid(),getppid());
}否则{
printf(“我是家长。我的pid是%d。我孩子的pid是%d\n”,getpid(),pid);
等待(空);
}
返回0;
}
int-pid代码>应定义为pid\u t pid
在子对象上设置父对象waitpid()
,这样子对象调用getppid()
时父对象仍在运行。fork()
函数有三个返回值:=0表示子对象,>0表示父对象,
#include <stdio.h>
#include <unistd.h>
int main(void)
{
int pid;
pid=fork();
if(pid==0) {
printf("I am the child.My pid is %d .My parents pid is %d \n",getpid(),getppid());
} else {
printf("I am the parent.My pid is %d. My childs pid is %d \n",getpid(),pid);
wait(NULL);
}
return 0;
}