gpt4 book ai didi

c - 子进程 pid() 是否被分配给父进程?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:08:38 28 4
gpt4 key购买 nike

我在书本和一些在线论坛上读到过,子进程 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 ProcessChild PID : 2061Parent PID : 1830In Child ProcessChild process PID : 2062Parent Process PID : 1161

But if I write a wait() function in else block, i.e:

#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 ProcessChild process PID : 2044Parent Process PID : 2043In Parent ProcessChild PID : 2043Parent PID : 1830

我不明白为什么第一个代码中子进程返回的 pid 值与父 pid 不同。而在第二个代码中,它是相同的。有人可以解释一下出现上述问题的原因吗?

最佳答案

请记住,getpid 返回当前 进程的 pid,getppid 返回当前 的父进程 pid em> 过程。

因此在第二个示例中,当您在父进程中调用 getpid 时,您将获得 if 自身(父进程)的 pid,而 getppid 将获得祖父 - parent 。

子 pid 是 fork 返回的值。


与您的问题更相关的是,您无法控制特定进程何时在现代多任务系统中运行,这意味着子进程和父进程可能会轮流打印文本。在您的情况下,第一个示例中的子进程似乎在父进程打印其行之前不会运行。

wait 函数的作用实际上是等待一个子进程退出,因此父进程将阻塞直到子进程退出。

关于c - 子进程 pid() 是否被分配给父进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32780406/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com