int main pid_t pid1pid2; ifpid1=fork = = 0 sleep3; printfinfo1 from child process_1n; exit0; printfinfo2 from child process_1n; else ifpid2=fork = = 0 sleep1; printfinfo1 from c
输出是: info1 from child process_2 info1 from child process_1 info1 from parent process info2 from parent process
这是因为在主进程中首先创建了两个子进程,pid1和pid2分别对应两个子进程。 在第一个子进程中,先执行了sleep(3)函数,等待3秒钟后输出"info1 from child process_1",然后执行了exit(0)函数,退出进程,所以后面的代码不会执行。 在第二个子进程中,先执行了sleep(1)函数,等待1秒钟后输出"info1 from child process_2",然后执行了exit(0)函数,退出进程,所以后面的代码不会执行。 在父进程中,通过wait(NULL)函数等待两个子进程退出,然后输出"info1 from parent process",再输出"info2 from parent process",最后调用_exit(0)函数退出进程。
原文地址: http://www.cveoy.top/t/topic/h4KT 著作权归作者所有。请勿转载和采集!