fork和vfork函数

fork函数  fork : 创建一个子进程
                  如果创建失败 返回 -1
                  成功返回两个值,如果是在父进程中,返回子进程的ID

                          如果是在子进程,返回值是0

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>


int main()
{
	
	pid_t pid = fork();
	if (pid == -1)
	{
		perror ("fork");
		return -1;
	}
	
	if (pid > 0)         // 父进程
	{
		printf ("我是父进程,pid = %d\n", getpid());
	}
	else if (pid == 0)   // 子进程
	{
		printf ("我是子进程,pid = %d\n", getpid());
	}

	
	while (1);
	
	return 0;
}

vfork函数
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

// 1、vfork 的子进程必须要显示调用 exit();

// 2、vfork 子进程和父进程共享数据段

// 3、vfork 的子进程先于父进程执行,子进程执行完,CPU才能调度到父进程
int main()
{
	int count = 0;
	
	pid_t pid = vfork();
	if (pid < 0)
	{
		perror("vfork");
		return -1;
	}
	
	count++;
	
	if (pid > 0)         // 父进程
	{
		printf ("我是父进程,pid = %d  count = %d\n", getpid(), count);
	}
	else if (pid == 0)   // 子进程
	{
		printf ("我是子进程,pid = %d  count = %d\n", getpid(), count);
		while (1);
		exit(0);
	}
	
	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值