是否将子进程pid()分配给父进程?
我在书本中以及在子进程的PID分配给其父一些网上论坛上阅读。但是,我有这样的代码:是否将子进程pid()分配给父进程?
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)
{
printf("In Child Process\n");
printf("Child process PID : %d\n",getpid());
printf("Parent Process PID : %d\n",getppid());
}
else
{
printf("In Parent Process\n");
printf("Child PID : %d\n",getpid());
printf("Parent PID : %d\n",getppid());
}
}
它输出:
In Parent Process Child PID : 2061 Parent PID : 1830 In Child Process Child process PID : 2062 Parent Process PID : 1161
但如果我写了等待中的其他块()函数,即:
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)
{
printf("In Child Process\n");
printf("Child process PID : %d\n",getpid());
printf("Parent Process PID : %d\n",getppid());
}
else
{
wait();
printf("In Parent Process\n");
printf("Child PID : %d\n",getpid());
printf("Parent PID : %d\n",getppid());
}
}
它输出 -
In Child Process Child process PID : 2044 Parent Process PID : 2043 In Parent Process Child PID : 2043 Parent PID : 1830
我没有得到为什么PID值retur第一个代码中的子进程ned与父进程pid不同。 而在第二个代码中,它是相同的。有人可以解释上述问题的原因吗?
记住getpid
返回当前进程的PID,以及getppid
返回当前进程的父进程的PID。
所以在第二个例子中,当你在父进程调用getpid
你得到的,如果本身(父进程)和getppid
得到盛大 -parent的PID的PID。
孩子PID是fork
返回的值。
更关系到你的问题是,你有当特定工艺在现代多任务系统,这意味着孩子与父进程可能需要把打印出的文本运行无法控制。在你的情况下,似乎第一个例子中的子进程在父进程打印其行之前不会运行。
wait
函数的作用是实际等待一个子进程退出,并且父进程将会阻塞,直到子进程退出。
勒夫的回答是优秀的。
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
int main()
{
pid_t pid;
pid=fork();
if(pid==0)
{
printf("In Child Process\n");
printf("Child process PID : %d\n",getpid());
printf("Parent Process PID : %d\n",getppid());
}
else
{
wait();
printf("In Parent Process\n");
printf("Child PID : %d\n", pid); // fork returns the pid of the child
printf("Parent PID : %d\n", getpid()); // because I'm the parent
}
}
第一个例子:作为附加的注释,您可以通过打印的fork
结果得到的子进程在else
分支的pid fork函数返回两个过程,在叉后你的第一个例子中,父母开始执行并打印其PID 2061和PID母公司1830(庆典)和母公司将终止,而无需等待孩子来完成,所以,当孩子开始执行它,将打印PID 2062及其母公司已经终止正在打印一些其他的PID。
请您打印父PID时,子进程在运行前及在其他终端使用命令ps -l看哪个的PID孩子正在打印作为父母睡PID()。
第二个例子:
您正在使用父进程的等待是家长会等待,直到孩子因此终止子进程正在打印正确parentpid因为父母仍然没有结束。
你看过吗,哪个过程实际上是1830?从我所记得的情况来看,如果父进程运行完毕,并且孤儿子进程仍然存在,则它可能是1830年的进程“init”。 – icbytes
@icbytes init进程始终是进程1.更有可能pid 1830是shell的pid。 –
然后它不是“init”,thx。 – icbytes