2011-09-01 128 views
5

我想创建一个使用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; 
} 

这将导致输出:

这是孩子的过程。我的pid是22163,父母的ID是0.
这是子进程。我的pid是22162,我的父母的编号是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 %d and my parent's id is %d.\n", getpid(), pid); 
} 

return 0; 
} 
+2

您的程序不会尝试在任何地方打印单词“父进程”。它们不在节目文本中,你为什么期望它们被打印? –

+3

'人叉'。阅读。理解单词。如果您没有任何方法可以自己查找答案,请转到StackOverflow。你将成为这种体验的更好的程序员。 – asveikau

+2

另外,'fork'不会将父进程ID返回给子进程。它返回0给孩子和孩子的ID给父母。这就是你如何知道哪个是哪个。 –

回答

9

首先阅读fork man page以及getppid/getpid手册页。

从叉的

成功时,子进程的PID在父的 线程执行的返回,以及0 执行的孩子的线程返回。失败时,-1将返回父代的上下文中, 将不会创建子进程,并且将适当地设置errno。

所以这应该是下降的

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是22163,父母的ID是0.

这是子进程。我的PID是22162,我的父母的ID是 22163.

fork()printf之前执行。所以当它完成时,你有两个进程执行相同的指令。因此,printf将执行两次。拨打fork()将返回子进程的0,并将子进程的pid返回到父进程。

你得到两个正在运行的进程,每一个将执行此 指令 声明:

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)。

+0

它会打印两次,因为...(来自fork的人):创建新的子进程后,两个进程都将执行fork()系统调用之后的下一条指令。因此,我们必须将父母与孩子区分开来。这可以通过测试fork()的返回值来完成 – Icarus

+0

非常感谢,这是一个很棒的故障。我编辑了我上面修改过的代码。它似乎正常工作。你介意重新检查一下,看看我的逻辑是正确的吗? – raphnguyen

+0

@raphnguyen每个人都应该调用'getppid()'来获取他们父进程的id。在您的示例中,父进程将打印其子进程标识。 – Tom

0

在打印两次,因为您呼叫的printf两次,一次在你的程序的执行,一旦在叉。尝试从printf调用中取出fork()。

2

它正在打印语句两次,因为它正在为父级和子级打印它。父为0

尝试这样的事情父ID:

pid_t pid; 
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(), getppid()); 
0

这是得到正确的输出正确的方式....但是,孩子的父ID也许有时打印为1,因为父进程终止,并且pid = 1的根进程控制着这个孤立进程。

pid_t pid; 
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); 
相关问题