fork函数
pid_t fork(void);
fork函数调用成功, 返回两次
在fork函数执行完毕后
如果创建新进程成功,则出现两个进程
一个是子进程,一个是父进程
在子进程中,fork函数返回0
在父进程中,fork返回新创建子进程的进程ID
我们可以通过fork返回的值来判断当前进程是子进程还是父进程。
返回值为0,代表当前进程是子进程
返回值是非负数,代表当前进程为父进程
调用失败,返回-1
返回值是pid_t 类型的,这里的pid_t类似一个类型,就像int型一样,int型定义的变量都是整型的,pid_t定义的类型都是进程号类型。这个语句的意思是定义了一个pid_t类型的变量pid,fork()函数返回一个进程号,这个进程号赋给了pid。
代码示例
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{pid_t pid;pid_t fpid;printf("father id :%d\n",getpid());fpid=fork();if(fpid>0){printf("this is father print,pid=%d\n",getpid());}else if(pid==0){printf("this is child print,pid=%d\n",getpid());}return 0;
}
运行结果:father id :17615this is father print,pid=17615this is child print,pid=17616
判断进程的运行顺序
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{pid_t pid;pid_t fpid;pid_t returnpid;printf("father id :%d\n",getpid());returnpid=fork();fpid=getpid();//获取当前进程的pid,父子进程都会执行这句话getppid()——获取父进程的pidif(fpid==pid){printf("this is father print,pid=%d,returnpid=%d\n",getpid(),returnpid);}else{printf("this is child print,pid=%d,returnpid=%d\n",getpid(),returnpid);}return 0;
}
运行结果:father id :17638this is child print,pid=17638,returnpid=17639this is child print,pid=17639,returnpid=0
子进程改变变量父进程中的变量不变
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{pid_t pid;pid_t fpid;int a=10;printf("father id :%d\n",getpid());fpid=fork();if(fpid>0){printf("this is father print,pid=%d\n",getpid());}else if(pid==0){printf("this is child print,pid=%d\n",getpid());a=a+10;}printf("a=%d\n",a);return 0;
}
运行结果: father id :17660this is father print,pid=17660a=10this is child print,pid=17661a=20
创建子进程的目的
模拟与客户端交互
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{pid_t fpid;int data;while(1){printf("please input a data\n");scanf("%d",&data);if(data==1){fpid=fork();if(fpid>0){}else if(fpid==0){while(1){printf("do net request,pid=%d\n",getpid());sleep(3);}}}else{printf("do nothing\n");}}return 0;
}
vfork函数
pid_t vfork(void);
用法和fork函数一样
代码示例
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{pid_t pid;pid=vfork();int cnt;if(pid>0){while(1){printf("this is father print,pid=%d\n",getpid());sleep(1);printf("cnt=%d\n",cnt);//和父进程共享内存,cnt的值被改变}}else if(pid==0){while(1){printf("this is child print,pid=%d\n",getpid());sleep(1);cnt++;if(cnt==3){exit(-1);}}}return 0;
}