进程创建:fork()函数
所需头文件:#include<sys/types.h>
#include<unistd.h>
函数原型:pid_t fork()
函数参数:无
函数返回值:
0 子进程
>0 父进程,返回值为创建出的子进程的PID
-1 出错
fork()函数用于从一个已经存在的进程内创建一个新的进程,新的进程称为“子进程”,相应地称创建子进程的进程为“父进程”。使用fork()函数得到的子进程是父进程的复制品,子进程完全复制了父进程的资源,包括数据区、堆区、栈区除了代码区等一切资源,父子进程共享代码区。
示例1:使用fork()函数创建子进程,父子进程分别输出不同的信息
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
pid_tpid;
pid= fork();//获得fork()的返回值,根据返回值判断父进程/子进程
if(pid==-1)//若返回值为-1,表示创建子进程失败
{
perror("cannotfork");
return-1;
}
elseif(pid==0)//若返回值为0,表示该部分代码为子进程
{
printf("Thisis child process\n");
printf("pidis %d, My PID is %d\n",pid,getpid());
}
else//若返回值>0,则表示该部分为父进程代码,返回值是子进程的PID
{
printf("Thisis parent process\n");
printf("pidis %d, My PID is %d\n",pid,getpid());
}
return0;
}
示例2:测试父子进程共享资源情况
示例代码:
/*************************************************************************
@Author: wanghao
@Created Time : Thu 17 May 2018 01:56:36 AM PDT
@File Name: fork.c
@Description:
************************************************************************/
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int global = 11;
char buf[64] = "the test content!";
int main(int argc, const char *argv[])
{
int stat;
int test = 0;
pid_t pid;
write(STDOUT_FILENO, buf, sizeof(buf));
printf("\n");
pid = fork();
if(pid == 0)
{
global++;
test++;
printf("This is child!\n");
strcat(buf, "this is child\n");
printf("pid %d, global = %d, test = %d, buf = %s\n",getpid(), global, test, buf);
exit(0);
}
if(pid > 0)
{
global++;
test++;
printf("This is parent!\n");
strcat(buf, "this is parent\n");
printf("pid %d, global = %d, test = %d, buf = %s\n",getpid(), global, test, buf);
exit(0);
}
return 0;
}
测试结果:
the test content!
This is parent!pid 3598, global = 12, test = 1, buf = the test content!this is parent
This is child!
pid 3599, global = 12, test = 1, buf = the test content!this is child
从测试结果,父子进程不共享数据段、栈、堆,只共享代码段。
为了提高效率,现代unix的fork在创建新进程时,并不产生副本,它通过允许父子进程可访问相同物理内存从而伪装了对进程地址空间的真实拷贝,当子进程改变内存中数据时才拷贝父进程,这就是“写操作时拷贝”(copy-on-write)技术。