相关疑难解决方法(0)

fork()子进程和父进程

我正在尝试创建一个使用fork()来创建新进程的程序.示例输出应如下所示:

这是子进程.我的pid是733,我父母的id是772.
这是父进程.我的pid是772,我孩子的id是773.

这是我编写程序的方式:

#include <stdio.h>
#include <stdlib.h>

int main() {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), fork());

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这导致输出:

这是子进程.我的pid是22163,我父母的id是0.
这是子进程.我的pid是22162,我父母的id是22163.

为什么它会两次打印语句?如何在第一句中显示子ID后如何正确显示父语句?

编辑:

#include <stdio.h>
#include <stdlib.h>

int main() {
int pid = fork();

if (pid == 0) {
    printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
else {
    printf("This is the parent process. My pid is …
Run Code Online (Sandbox Code Playgroud)

c fork parent

6
推荐指数
1
解决办法
11万
查看次数

标签 统计

c ×1

fork ×1

parent ×1