linux创建进程fork函数和vfork函数

博客介绍了fork和vfork函数创建子进程的相关知识。fork函数调用一次返回两次,子进程返回0,父进程返回子进程ID,创建的子进程复制父进程内存空间,父、子进程运行顺序由系统调度;vfork函数创建的子进程先运行,且不复制父进程内存空间。
       #include <unistd.h>

       pid_t fork(void);

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

       pid_t vfork(void);

返回:子进程中为0,父进程中为子进程ID,出错返回  -1

 

fork创建的新进程被称为子进程,该函数被调用一次但是返回两次,两次返回的区别是:在子进程中的返回值是,在父进程中的返回值是新的子进程的进程ID;

创建子进程,父进程哪个先运行根据系统的调度且复制父进程的内存空间。


vfork函数,创建子进程,但是子进程先运行且不复制父进程的内存空间。

 

fork函数示例:

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



int		glob = 6;		/* external variable in initialized data */
char	buf[] = "a write to stdout\n";

int
main(void)
{
	int		var;		/* automatic variable on the stack */
	pid_t	pid;

	var = 88;
	if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
		perror("write error");
	printf("before fork\n");	/* we don't flush stdout */

	if ((pid = fork()) < 0) {
		perror("fork error");
	} else if (pid == 0) {		/* child */
		glob++;					/* modify variables */
		var++;
	} else {
		sleep(2);				/* parent */
	}

	printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
	exit(0);
}

编译之后运行结果:

andrew@andrew-Thurley:~/work/apue.2e$ ./a.out
a write to stdout
before fork
pid = 16935, glob = 7, var = 89
pid = 16934, glob = 6, var = 88

 

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




int		glob = 6;		/* external variable in initialized data */

int
main(void)
{
	int		var;		/* automatic variable on the stack */
	pid_t	pid;

	var = 88;
	printf("before vfork\n");	/* we don't flush stdio */
	if ((pid = vfork()) < 0) {
		perror("vfork error");
	} else if (pid == 0) {		/* child */
		glob++;					/* modify parent's variables */
		var++;
		_exit(0);				/* child terminates */
	}

	/*
	 * Parent continues here.
	 */
	printf("pid = %d, glob = %d, var = %d\n", getpid(), glob, var);
	exit(0);
}

 

编译之后运行结果:

andrew@andrew-Thurley:~/work/apue.2e$ ./a.out
before vfork
pid = 17047, glob = 7, var = 89

 

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

andrewbytecoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值