"输出是:\ninfo1 from child process_2\ninfo1 from child process_1\ninfo1 from parent process\ninfo2 from parent process\n\n这是因为在主进程中首先创建了两个子进程,pid1和pid2分别对应两个子进程。\n在第一个子进程中,先执行了sleep(3)函数,等待3秒钟后输出"info1 from child process_1",然后执行了exit(0)函数,退出进程,所以后面的代码不会执行。\n在第二个子进程中,先执行了sleep(1)函数,等待1秒钟后输出"info1 from child process_2",然后执行了exit(0)函数,退出进程,所以后面的代码不会执行。\n在父进程中,通过wait(NULL)函数等待两个子进程退出,然后输出"info1 from parent process",再输出"info2 from parent process",最后调用_exit(0)函数退出进程。\n\n"int main()\n{ pid_t pid1,pid2; \n if((pid1=fork()) = = 0)\n{\n sleep(3);\n printf("info1 from child process_1\n");\n exit(0);\n printf("info2 from child process_1\n"); \n}\nelse\n{\n if((pid2=fork()) = = 0)\n {\n sleep(1);\n printf("info1 from child process_2\n");\n exit(0);\n }\nelse\n {\n wait(NULL);\n wait(NULL);\n printf("info1 from parent process\n");\n printf("info2 from parent process");\n _exit(0);\n }} \n


原文地址: https://www.cveoy.top/t/topic/pNFy 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录