Pipe

无名管道:

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

int read_pipe(int fd)
{
	int n;
	char buf[1024];
	
	while(1)
	{
		n = read(fd,buf,sizeof(buf) - 1);
		buf[n] = '\0';

		printf("Read %d bytes: %s.\n",n,buf);

		if(strncmp(buf,"quit",4) == 0)
			break;
	}

	return 0;
}

int write_pipe(int fd)
{
	
	/*
	char buf[] = "hello word";
	sizeof(buf) : 11
	strlen(buf) : 10
	*/
	char buf[1024];

	while(1)
	{
		printf(">");
		fgets(buf,sizeof(buf),stdin);
		buf[strlen(buf) - 1] = '\0';

		write(fd,buf,strlen(buf));

	}
}

int main(int argc, const char *argv[])
{
	pid_t pid;
	int fd[2];

	if(pipe(fd) < 0)
	{
		perror("Fail to pipe");
		exit(EXIT_FAILURE);
	}

	if((pid = fork()) < 0)
	{
		perror("fail to fork");
		exit(EXIT_FAILURE);
	}

	if(pid == 0)
	{
		close(fd[1]);
		read_pipe(fd[0]);
	}

	if(pid > 0)
	{
		close(fd[0]);
		write_pipe(fd[1]);
	}
	
	exit(EXIT_SUCCESS);
}

pipe 读写操作

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

int read_pipe(int r_fd,const char *filename)
{
	int n;
	int file_fd;
	char buf[1024];

	if((file_fd = open(filename,O_WRONLY | O_CREAT | O_TRUNC,0666)) < 0)
	{
		fprintf(stderr,"Fail to open %s : %s.\n",filename,strerror(errno)); 
		exit(EXIT_FAILURE);
	}
	
	while(1)
	{
		n = read(r_fd,buf,sizeof(buf));
		if(n == 0)
			break;
		//错误
		//write(filename,buf,strlen(buf));
		write(file_fd,buf,n);
	}

	close(file_fd);
	close(r_fd);

	return 0;
}

int write_pipe(int w_fd,const char *filename)
{
	int n;
	int file_fd;
	char buf[1024];

	if((file_fd = open(filename,O_RDONLY)) < 0)
	{
		fprintf(stderr,"Fail to open %s : %s.\n",filename,strerror(errno)); 
		exit(EXIT_FAILURE);
	}

	while(1)
	{
		n = read(file_fd,buf,sizeof(buf));
		if(n == 0)
			break;

		write(w_fd,buf,n);
	}

	close(w_fd);
	close(file_fd);

	return 0;
}

//./a.out src dest
int main(int argc, const char *argv[])
{
	pid_t pid;
	int pipe_fd[2];

	if(argc < 3)
	{
		fprintf(stderr,"Usage : %s src dest.\n",argv[0]);
		exit(EXIT_FAILURE);
	}

	if(pipe(pipe_fd) < 0)
	{
		perror("Fail to pipe");
		exit(EXIT_FAILURE);
	}

	if((pid = fork()) < 0)
	{
		perror("Fail to fork");
		exit(EXIT_FAILURE);
	}

	if(pid == 0)
	{
		close(pipe_fd[1]);
		read_pipe(pipe_fd[0],argv[2]);
	}

	if(pid > 0)
	{
		close(pipe_fd[0]);
		write_pipe(pipe_fd[1],argv[1]);
	}
	
	exit(EXIT_SUCCESS);
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

静思心远

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

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

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

打赏作者

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

抵扣说明:

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

余额充值