进程A创建了进程B,则称进程A为父进程,进程B为子进程
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid_t pid2;
pid_t retpid;
pid = getpid();
printf("father: id=%d\n",pid);
retpid = fork();
pid2 = getpid();
printf("after fork: pid = %d\n",pid2);
if (pid==pid2){
printf("this is father print,retpid = %d\n",retpid);
}
else{
printf("this is child print,retpid=%d,child pid = %d\n",retpid,getpid());
}
return 0;
}
pid_t fork(void);
返回值为0,代表当前进程是子进程
返回值为非负数(子进程pid),代表当前进程为父进程
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid;
int data = 10;
printf("father: 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 print,child pid = %d\n",getpid());
data=data+10;
}
printf("data=%d\n",data);
return 0;
}
现在Linux采用Copy-On-Write(写时拷贝),当子进程不修改data这个变量时,是父进程共享这个变量,只有要修改data值时才会在自己的地址空间拷贝data变量。
旧的Liunx是把变量都先拷贝一份。
父、子进程共享正文段。
fork创建一个子进程的一般目的:
(1)一个父进程希望复制自己,使父、子进程同时执行不同的代码段。这在网络服务进程中是最常见的——父进程等待客户端的服务请求。当这种请求到达时,父进程调用fork,是子进程处理此请求。父进程则继续等待下一个服务请求到达。
(2)一个进程要执行一个不同的程序,这对shell是常见的情况。这种情况下。子进程从fork放回后立即调用exec。
vfork函数和fork函数的区别:
(1)vfrok直接使用父进程存储空间,不拷贝。
(2)vfork保证子进程先运行,当子进程调用exit退出后,父进程才执行。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
pid_t pid;
int cnt = 0;
pid = vfork();
if (pid>0){
while(1){
printf("cnt=%d\n",cnt);
printf("this is father print,pid = %d\n",getpid());
sleep(1);
}
}
else if(pid==0){
while(1){
printf("this is child print,child pid = %d\n",getpid());
sleep(1);
cnt++;
if(cnt == 3){
exit(0);
}
}
}
return 0;
}