⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 prg4_2.c

📁 配套光盘网络编程进程间的通信,网络编程进程间的通信是一本很经典的好书
💻 C
字号:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#define 	MAXLINE  100
void client(int ,int),server(int,int);
int main(int argc,char ** argv)
{
	int    pipe1[2],pipe2[2];
	pid_t  childpid;
	//创建两个管道
	pipe(pipe1);
	pipe(pipe2);
	if ((childpid = fork()) == 0)	//子进程
	{
		close(pipe1[1]);	
		close(pipe2[0]);
		
		server(pipe1[0],pipe2[1]);
		exit(0);
	}
	else if (childpid >0)	//父进程
	{
		close(pipe1[0]);
		close(pipe2[1]);
		client(pipe2[0],pipe1[1]);
		waitpid(childpid,NULL,0);
		exit(0);
	}
	else
	{
		printf("fork error\n");
		exit(0);
	}
}

void client(int readfd,int writefd)
{
	size_t		len;
	size_t		n;
	char			buff[MAXLINE];
	
	//从命令行中读入一个路径到IPC管理
	fgets(buff,MAXLINE,stdin);
	len = strlen(buff);
	if (buff[len-1] == '\n')
		len-- ;
	write(writefd,buff,len);
	//read from IPC ,write to standard output
	while( (n=read(readfd,buff,MAXLINE)) >0)
			write(STDOUT_FILENO,buff,n);
}

void server(int readfd,int writefd)
{
	int				fd;
	size_t		n;
	char			buff[MAXLINE+1];
	
	if ( ( n= read(readfd,buff,MAXLINE)) == 0)
	{
				perror("end-of-file while reading pathname");
				exit(0);
	}
	buff[n] = '\0';
	if ((fd = open(buff,O_RDONLY)) <0)
	{
		snprintf(buff+n,sizeof(buff)-n,":can't open, %s\n",strerror(errno));
		n = strlen(buff);
		write(writefd,buff,n);
	}
	else
	{
		while( (n=read(fd,buff,MAXLINE)) >0)
				write(writefd,buff,n);
		close(fd);
	}
}
			
	
		

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -