使用fork函数创建一个进程 pid_t fork(void); fork函数调用成功,返回两次值为0,代表当前进程的子进程。返回值非负数,代表当前进程为父进程,调用失败 返回1;
实例1:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
pid_t pid;
printf("farter : id = %d\n",getpid());
pid = fork();
if(pid>0){//父进程
printf("this is father print pid = %d\n",getpid());//检验父进程
}
else if(pid == 0){子进程
printf("this is child pid =%d\n",getpid());检验子进程
}
return 0;
}
实例2:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
int main()
{
pid_t pid;
pid_t pid2;
pid_t retpid;
int data = 10;
pid = getpid();
printf("before fork : pid = %d\n",pid);
retpid = fork();
pid2 = getpid();
printf("after fork pid = %d\n",pid2);
if(pid == pid2){
printf("this is farther print %d\n",retpid);
}
else{
printf("this is child print chil return pid= %d, pid = %d\n",retpid,getpid());
data = data+10;
}
printf("data = %d\n",data);
return 0;
}
结果
cuichao@ubuntu:~/c语言$ gcc fork.c
cuichao@ubuntu:~/c语言$ ./a.out
before fork : pid = 7931
after fork pid = 7931
this is farther print 7932
data = 10
after fork pid = 7932
this is child print chil return pid= 0, pid = 7932
data = 20
运行效果发现,父进程复制自己,使父、子进程同时进行不同代码
目的:
1、一个父进程希望复制自己,使父、子进程同时进行不同的代码段,这在网络服务器进程中是常见的——父进程等待客户端的服务请求。当这种请求到达时,父进程调用fork,使子进程处理此要求。父进程则继续等待下一个服务请求达到
2、一个进程要执行一个不同的程序。这对sehll使常见的情况。在这中情况下,子进程从fork返回后立即调用exec