pid_t pid = fork();
它可能有三种不同的返回值:
1)在父进程中,fork返回新创建子进程的进程ID;
2)在子进程中,fork返回0;
3)如果出现错误,fork返回一个负值;
父子进程分别运行代码,体现了一个分裂的过程。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <signal.h>
main(int argc, char const *argv[])
{
int i;
for (i = 0;i<5;i++){
//创建新的进程
pid_t pid = fork();
//pid=0 代表子进程
if(pid == 0){
break;
}
}
//在这之后我们就有父进程和子进程分别跑下面的代码
//子进程
if(i == 2){
printf("I will kill father after 5\n");
sleep(5);
kill(getppid(),SIGKILL);
while(1){
sleep(1);
}
}
//父进程
else if(i == 5){
while(1){
printf("I am father\n");
sleep(1);
}
}
return 0;
}