Linux下进程间使用管道通信

原文链接: https://my.oschina.net/IMLYC/blog/134963
#include 
#include 
#include 
#include 
#include 

//父进程
void pProc(int fd0,int fd1)
{
	char buf[513];
	int len = 0;
	int i;
	
	printf("> My pid is %d,my parent is %d.\n",getpid(),getppid());
	do
	{
		len = read(fd0,buf,sizeof(buf) - 1);
		buf[len] = 0;//结束字符串
		printf("> %s",buf);
	}while(len);
	close(fd0);
	printf("\n> Parent exited\n");
}

//子进程
void cProc(int fd0,int fd1)
{
	char buf[513];
	int len;
	
	sprintf(buf,"My pid is %d,my parent is %d.\n",getpid(),getppid());
	do
	{
		len = strlen(buf);
		write(fd1,buf,len + 1);//传输len+1长度以便把字符串结束符发送过去
		//延时1ms以等待父进程输出
		usleep(100);
		printf(">> ");
	}while(fgets(buf,sizeof(buf)-1,stdin));
	close(fd1);
	printf("\n>> Child exited\n");
}

int main(int argc,char *argv[])
{
	int fd_p2c[2] = {0};
	int fd_c2p[2] = {0};
	int pid;

	if (pipe(fd_p2c) < 0)
	{
		perror("Pipe fd_p2c create fail.\n");
		return -1;
	}
	if (pipe(fd_c2p) < 0)
	{
		perror("Pipe fd_c2p create fail.\n");
		return -1;
	}
	
	pid = fork();
	
	if(pid == 0)
	{
		//关闭不用的文件描述符
		close(fd_p2c[1]);
		close(fd_c2p[0]);
		cProc(fd_p2c[0],fd_c2p[1]);
	}
	else if(pid < 0)
	{
		perror("Child process create fail.");
		return -2;
	}
	else
	{
		//关闭不用的文件描述符
		close(fd_p2c[0]);
		close(fd_c2p[1]);
		pProc(fd_c2p[0],fd_p2c[1]);
	}
	
	return 0;
}

转载于:https://my.oschina.net/IMLYC/blog/134963

你可能感兴趣的:(Linux下进程间使用管道通信)