问题描述
我正在尝试创建一个使用fork()创建新进程的程序.示例输出应如下所示:
I am trying to create a program that uses fork() to create a new process. The sample output should look like so:
这是子进程.我的pid是733,父母的ID是772.
这是父进程.我的pid是772,孩子的ID是773.
This is the child process. My pid is 733 and my parent's id is 772.
This is the parent process. My pid is 772 and my child's id is 773.
这是我编写程序的方式:
This is how I coded my program:
#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;
}
这将导致输出:
这是子进程.我的pid是22163,父母的ID是0.
这是子进程.我的pid是22162,我父母的ID是22163.
This is the child process. My pid is 22163 and my parent's id is 0.
This is the child process. My pid is 22162 and my parent's id is 22163.
为什么要打印两次语句,在第一句话中显示孩子的ID后,如何才能正确显示父母的ID?
Why is it printing the statement twice and how can I get it to properly show the parent's id after the child id displays in the first sentence?
#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 %d and my parent's id is %d.\n", getpid(), pid);
}
return 0;
}
推荐答案
Start by reading the fork man page as well as the getppid / getpid man pages.
从叉子的
所以这应该是
if ((pid=fork())==0){
printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
printf("Dont yada yada me, im your parent with pid %u ", getpid());
}
关于您的问题:
这是子进程.我的PID是22162,我父母的ID是 22163.
This is the child process. My pid is 22162 and my parent's id is 22163.
fork()
在printf
之前执行.因此,完成后,您将具有两个具有相同指令执行的进程.因此,printf将执行两次.调用fork()
会将0
返回到子进程,并将子进程的pid
返回到父进程.
fork()
executes before the printf
. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork()
will return 0
to the child process, and the pid
of the child process to the parent process.
您有两个正在运行的进程,每个进程都将执行以下语句:
You get two running processes, each one will execute this statement:
printf ("... My pid is %d and my parent's id is %d",getpid(),0);
和
printf ("... My pid is %d and my parent's id is %d",getpid(),22163);
〜
最后,上面的行是子级,指定其pid
.第二行是父进程,指定其ID(22162)和其子进程(22163).
To wrap it up, the above line is the child, specifying its pid
. The second line is the parent process, specifying its id (22162) and its child's (22163).
这篇关于fork()子进程和父进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!