子进程和父进程ID [英] child and parent process id
问题描述
只是在子进程块中与父pid值混淆了.我的程序如下:
Just got confused with parent pid value in child process block. My program is given below:
int main(int argc, char *argv[])
{
pid_t pid;
pid=fork();
if(pid==-1){
perror("fork failure");
exit(EXIT_FAILURE);
}
else if(pid==0){
printf("pid in child=%d and parent=%d\n",getpid(),getppid());
}
else{
printf("pid in parent=%d and childid=%d\n",getpid(),pid);
}
exit(EXIT_SUCCESS);
}
输出: parent = 2642和childid = 2643中的pid
Output: pid in parent=2642 and childid=2643
pid = child = 2643 and parent = 1
pid in child=2643 and parent=1
在高级Unix编程"中,它表示子进程可以使用getppid()函数获取父进程ID.但是在这里,我得到的是"1",它是"init"进程ID.
In "Advanced Unix programming" it says that child process can get parent process id using getppid() function. But here I am getting "1" which is "init" process id.
如何在子进程块中获取父pid值.请帮助我获取输出.
How can I get the parent pid value in the child process block.. Please help me in getting output.
我在"Linux Mint OS"中执行,但是在"WindRiver" OS中我没有遇到这个问题.该程序会根据操作系统更改行为吗?
I executed in "Linux Mint OS" but in "WindRiver" OS I am not getting this problem. Does this program change behaviour according to OS?
推荐答案
这是因为父亲可以/将在儿子之前退出.如果一个父亲存在而没有请求其孩子的返回值,则该孩子将被pid = 1的进程所拥有.在经典UNIX或GNU系统SystemV init上是什么.
That's because the father can / will exit before the son. If a father exists without having requested the return value of it's child, the child will get owned by the process with pid=1. What is on classic UNIX or GNU systems SystemV init.
解决方案是在父亲中使用waitpid()
:
The solution is to use waitpid()
in father:
int main(int argc, char *argv[])
{
pid_t pid;
pid=fork();
if(pid==-1){
perror("fork failure");
exit(EXIT_FAILURE);
}
else if(pid==0){
printf("pid in child=%d and parent=%d\n",getpid(),getppid());
}
else{
printf("pid in parent=%d and childid=%d\n",getpid(),pid);
}
int status = -1;
waitpid(pid, &status, WEXITED);
printf("The child exited with return code %d\n", status);
exit(EXIT_SUCCESS);
}
这篇关于子进程和父进程ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!