2025思明装修公司口碑指南:高性价比+本土实力品牌全解析 - 品牌测评鉴赏家
2025/12/29 15:16:48
#include<unistd.h>pid_tfork(void);#include<stdio.h>#include<sys/types.h>#include<unistd.h>intmain(intargc,constchar*argv[]){pid_tpid=fork();if(pid<0){perror("fork");return-1;}elseif(pid>0){printf("这里是父进程\n");}else{printf("这里是子进程\n");}while(1)sleep(1);return0;}fork()带来的问题#include<sys/types.h>#include<unistd.h>#include<stdio.h>intmain(intargc,constchar*argv[]){pid_tpid;for(inti=0;i<4;i++){pid=fork();if(pid<0){perror("fork");return-1;}elseif(pid==0){printf("child process\n");}else{printf("parent process\n");}}intt=100;while(t--)sleep(1);return0;}fork─┬─fork─┬─fork─┬─fork───fork │ │ └─fork │ ├─fork───fork │ └─fork ├─fork─┬─fork───fork │ └─fork ├─fork───fork └─fork#include<sys/types.h>#include<unistd.h>#include<stdio.h>intmain(intargc,constchar*argv[]){pid_tpid;for(inti=0;i<4;i++){pid=fork();if(pid<0){perror("fork");return-1;}elseif(pid==0){printf("child process\n");}else{printf("parent process\n");break;}}intt=100;while(t--)sleep(1);return0;}$ pstree7658fork02───fork02───fork02───fork02───fork02#include<sys/types.h>#include<unistd.h>#include<stdio.h>intmain(intargc,constchar*argv[]){pid_tpid;for(inti=0;i<4;i++){pid=fork();if(pid<0){perror("fork");return-1;}elseif(pid==0){printf("child process\n");break;}else{printf("parent process\n");}}intt=100;while(t--)sleep(1);return0;}$ pstree -p16911fork(16911)─┬─fork(16912)├─fork(16913)├─fork(16914)└─fork(16915)return语句之后,就会结束,并通过return语句返回main函数当中执行return n等同于执行对exit(n)的调用return,或是无声无息地执行到main()函数结尾,同样会导致main()的调用者执行exit()函数,不同的C语言标准对此有不同的规定:C89未规定具体的返回值C99标准则要求,执行至main函数结尾处的情况应等同于调用exit(0)注意:开发当中,应避免只写return,避免return 没有明确的返回值
#include<stdio.h>#include<stdlib.h>#include<unistd.h>intmain(void){printf("Hello World!");switch(fork()){case-1:perror("fork error");return-1;case0:exit(0);default:return1;}return1;}exit()主要完成两件事:#include<unistd.h>void_exit(intstatus);_exit()的status参数定义了进程的终止状态(termination status)shell当中可以通过echo $?得到status的值_exit()的程序总会成功终止(程序都结束了,再检查返回值已经没有意义了)#include<stdio.h>#include<stdlib.h>#include<unistd.h>intmain(void){printf("Hello World!");switch(fork()){case-1:perror("fork error");exit(-1);case0:_exit(0);default:exit(0);}}_exit()