进程创建-fork()

进程创建: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)技术。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值