子进程使用exec启动新程序时管道的使用

直白来说就是子进程直接在新的程序中运行!
a.功能实现:
有程序P1, P2
使用管道进行通信
P1由用户输入一个字符串,然后把该字符串发给p2
P2接收到以后,把该字符串打印出来

b 难点:子进程使用exec启动新程序运行后,
新进程能够使用原来子进程的管道(因为exec能共享原来的文件描述符)
但问题是新进程并不知道原来的文件描述符是多少!

解决方案:
把子进程中的管道文件描述符,用exec的参数传递给新进程。
p1:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) 
{
	int fd[2];
	int ret;
	char buff1[1024];
	char buff2[1024];
	pid_t pd;

	ret = pipe(fd);
	if (ret !=0) {
		printf("create pipe failed!\n");
		exit(1);
	}

	pd = fork();
	if (pd == -1) {
		printf("fork error!\n");
		exit(1);
	} else if (pd == 0) {
		//bzero(buff2, sizeof(buff2));
		sprintf(buff2, "%d", fd[0]);
		execl("main3_2", "main3_2", buff2, 0);
		printf("execl error!\n");
		exit(1);
	} else {
		strcpy(buff1, "Hello!");
		write(fd[1], buff1, strlen(buff1)); 
		printf("process(%d) send information:%s\n", getpid(), buff1);
	}

	if (pd > 0) {
		wait();
	}
	
	return 0;	
}

p2:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]) 
{
	int fd;
	char buff[1024] = {0,};

	sscanf(argv[1], "%d", &fd);
	read(fd, buff, sizeof(buff));

	printf("Process(%d) received information:%s\n",  getpid(), buff);	
	return 0;	
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值