读书笔记之UNIX环境高级编程(8)

进程控制
1._exit并不执行标准I/O缓冲的冲洗动作
2.vfork()不对复制父进程空间,而是共享在父进程中运行,vfork保证子进程先运行,在他调用exec或exit后父进程才运行
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/sem.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>

int glob = 6;


int main(int argc, char* argv[])
{
	int var = 88;
	int pid = fork();
	if(pid < 0)
	{
		exit(0);
	}
	if(pid == 0)
	{

		++ var;
		++ glob;

		printf("child:%d,%d\n", var, glob);
		exit(0);
	}else
	{
		++ var;
		printf("father:%d,%d\n", var, glob);
	}
	wait(NULL);
	return 0;
}

father:89,6

child:89,7

结果说明,父子进程不共享全局变量和局部变量,子进程执行的是写时复制

#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/sem.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>

int glob = 6;


int main(int argc, char* argv[])
{
	int var = 88;
	int pid = vfork();
	if(pid < 0)
	{
		exit(0);
	}
	if(pid == 0)
	{

		++ var;
		++ glob;
		sleep(1);
		printf("child:%d,%d\n", var, glob);
		exit(0);
	}else
	{
		++ var;
		++ glob;
		printf("father:%d,%d\n", var, glob);
	}
	wait(NULL);
	return 0;
}
child:89,7
father:90,8

vfork的子进程与父进程共享地址空间

3.调用vfork的main函数要exit(0)退出,如果用return 会出现段错误,子进程return返回到他的调用处,返回信息保存在main栈帧中,父进程继续运行但堆栈内容已被修改,就会出现段错误

#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/sem.h>
#include <fcntl.h>
#include <semaphore.h>
#include <pthread.h>

int glob = 6;
void sum()
{
	int pid = vfork();
	if(pid < 0)
	{
		exit(0);
	}
	if(pid == 0)
	{


		++ glob;
		//sleep(1);
		printf("child:%d\n", glob);

	}else
	{

		++ glob;
		printf("father:%d\n", glob);
	}

}

int main(int argc, char* argv[])
{
	int var = 88;
	sum();
	//int pid = vfork();

	return 0;
}

child:7
father:8
a.out: cxa_atexit.c:100: __new_exitfn: Assertion `l != ((void *)0)' failed.
Aborted (core dumped)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值