使用fork函数创建一个进程
pid_t fork(void0);
fork函数调用成功,返回两次
返回值为0 代表当前进程是子进程
返回值非负数,代表当前进程为父进程
调用失败,返回-1
输入指令查看
tianya@tianya-virtual-machine:~$ man fork
NAME
fork - create a child process
SYNOPSIS
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
测试代码
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("father: id=%d\n",getpid());
pid=fork();//返回值为0 代表当前进程是子进程;返回值非负数,代表当前进程为父进程
if(pid>0)//fork函数成功调用,则父进程中返回所创建的子进程的ID
{
printf("this is father fork father ID=%d\n",getpid());
}
else if(pid==0)//fork函数成功调用,子进程中返回0
{
printf("this is chilid ,chilid pid=%d\n",getpid());
}
while(1);
return 0;
}
测试结果:当代码运行到fork前;得到父进程的pid; 调用fork成功后,通过返回值判断打印相应信息,从而确定该进程属于那一项进程
补充为什么fork函数会返回两次?
函数返回值:会返回两次,一次在父进程中,一次在子进程中,在父进程中返回所创建的子进程的ID,在子进程中返回0
成功:子进程中返回 0,父进程中返回子进程PID
失败:父进程中返回-1,子进程创建失败,无返回值,errorno被设置
tianya@tianya-virtual-machine:~$ gcc test3.c
tianya@tianya-virtual-machine:~$ ./a.out
father: id=6001
this is father fork father ID=6001
this is chilid ,chilid pid=6002
验证子进程中返回 0,父进程中返回子进程PID demo
1 #include<stdio.h>
2 #include <sys/types.h>
3 #include <unistd.h>
4 int main()
5 {
6
7 pid_t pid;
8 pid_t pid2;
9 pid_t retpid;
10
11 pid = getpid();
12
13 printf("befor: id=%d\n",pid);
14
15 retpid=fork();
16
17
18 pid2 = getpid();
19 printf("after fork:pid=%d\n",pid2);
20
21 if(pid==pid2)
22 {
23 printf("this is father print:iretppid=%d\n",retpid);
24
25 }
26 else
27 {
28
29 printf("this is chilid print,print,retpid=%d,chilid pid=%d\n",retpid,getpid());
30 }
31
32 while(1);
33 return 0;
34
35 }
结果
cai@cai-virtual-machine:~$ gcc test1.c
cai@cai-virtual-machine:~$ ./a.out
befor: id=84809
after fork:pid=84809
this is father print:iretppid=84810
after fork:pid=84810
this is chilid print,print,retpid=0,chilid pid=84810