主题:请教有关fork()函数的执行流程????
一段小程序如下:
int main(int argc, char **argv)
{
int val, stat;
pid_t child;
printf("\nTry to create new process.\n");
child = fork();
switch(child)
{
case -1: // fault
perror("fork.\n");
exit(EXIT_FAILURE);
case 0: // child process
printf("This is child.\n");
printf("\tchild pid is %d\n", getpid());
printf("\tchild ppid is %d\n", getppid());
exit(EXIT_SUCCESS);
default: // father process
waitpid(child, &stat, 0);
printf("This is parent.\n");
printf("\tparent pid is %d\n", getpid());
printf("\tparent ppid is %d\n", getppid());
printf("\tchild exited with %d\n", stat);
}
exit(EXIT_SUCCESS);
}
程序执行后的结果为:
This is child.
child pid is 3542
child ppid is 3535
This is parent.
parent pid is 3535
parent ppid is 3534
child exited with 0
Program exited normally.
由此可见:
程序是成功执行了语句perror("fork.\n")。
但本人就不明白,成功执行后不是返回值0,然后下面的switch语句执行,就只会执行case 0的情况么,接着就会exit(EXIT_SUCCESS)退出程序,为什么还有后面的结果呢???
请指点一下fork()调用的执行流程,谢谢!!!!
int main(int argc, char **argv)
{
int val, stat;
pid_t child;
printf("\nTry to create new process.\n");
child = fork();
switch(child)
{
case -1: // fault
perror("fork.\n");
exit(EXIT_FAILURE);
case 0: // child process
printf("This is child.\n");
printf("\tchild pid is %d\n", getpid());
printf("\tchild ppid is %d\n", getppid());
exit(EXIT_SUCCESS);
default: // father process
waitpid(child, &stat, 0);
printf("This is parent.\n");
printf("\tparent pid is %d\n", getpid());
printf("\tparent ppid is %d\n", getppid());
printf("\tchild exited with %d\n", stat);
}
exit(EXIT_SUCCESS);
}
程序执行后的结果为:
This is child.
child pid is 3542
child ppid is 3535
This is parent.
parent pid is 3535
parent ppid is 3534
child exited with 0
Program exited normally.
由此可见:
程序是成功执行了语句perror("fork.\n")。
但本人就不明白,成功执行后不是返回值0,然后下面的switch语句执行,就只会执行case 0的情况么,接着就会exit(EXIT_SUCCESS)退出程序,为什么还有后面的结果呢???
请指点一下fork()调用的执行流程,谢谢!!!!