一直在练习这些系统调用,但我坚持使用这段代码:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
main()
{
pid_t pid;
switch(pid = fork())
{
case -1:
printf("fork failed");
break;
case 0: //first child
printf("\ni'm the first child, my pid is %d", getpid());
fflush(stdout);
break;
default: //parent
sleep(5); /** sleep is generating problems **/
printf("\ni'm the parent process, my pid is %d", getpid());
printf("\ngenerating a new child");
fflush(stdout);
switch(pid = fork())
{
case -1:
printf("fork failed");
break;
case 0: //second child
printf("\nhere i am, the second child, my pid is %d", getpid());
break;
default: //parent
wait((int *)0);
printf("\nback to parent, my pid is %d", getpid());
}
}
return 0;
}
我得到的输出是:
i'm the first child, my pid is 6203
i'm the parent process, my pid is 6202
generating a new child
back to parent, my pid is 6202
Process returned 0 (0x0) execution time: 5.004 s
Press ENTER to continue
here i am, the second child, my pid is 6204
我正在尝试的是这些消息的简单打印,通过管理时间sleep()
。
我不明白为什么程序在打印第二条子消息之前返回。
默认情况(第二个分叉之后的那个)在其子项(第二个)作用于输出之前被打印,就像他忽略了它一样wait()
。因此,它的子进程在进程返回后被打印。
我无法弄清楚出了什么问题。我已经标记了 sleep() 函数,因为如果我用它替换它wait((int *)0);
流程流量按照其设计的方式运行(无论如何,没有任何时间安排)。
此时,我不再确定进程流量或 sleep() 用法(手册页没有那么有用,说实话太简洁了)。