5.3 shell中的管道实现

1、实验代码
dup.c

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

int main1 (void)
{
	int fd, new_fd;
	fd = open ("write.txt", O_RDWR | O_CREAT, 0644);
	if (fd == -1)
	{
		perror ("open");
		exit (EXIT_FAILURE);
	}
	new_fd = dup (fd);
    printf ("fd = %d\nnew_fd = %d\n", fd, new_fd);
	write (fd, "hello", strlen("hello"));
	close (fd);
	write (new_fd, "world", strlen("world"));
	close (new_fd);
	return 0;
}

int main (void)
{
	int new_fd;
	new_fd = dup (1);
	write (1, "hello", strlen("hello"));
	write (new_fd, "world\n", strlen("world\n"));
	close (new_fd);
	return 0;
}



```css


dup2.c

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

#define handler_error(msg) \
    {perror(msg);exit(EXIT_FAILURE);}

int main (void)
{
	int fd, new_fd;
	char *buf = "hello world\n";

	fd = open ("data.log", O_RDWR | O_CREAT, 0644);
	if (fd == -1)
        handler_error("open");

	new_fd = dup2 (fd, 1);
	if (new_fd == -1)
        handler_error("dup2");

	printf ("fd: %d\n new_fd: %d\n", fd, new_fd);
	write (1, buf, strlen(buf));
	close (fd);

	return 0;
}

pipe-dup.c

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

int main (void)
{
	int pipe_fd[2];
	if (pipe (pipe_fd) == -1)
	{
		perror ("pipe");
		exit (EXIT_FAILURE);
	}
	else
	{
		int ret_from_fork;
		ret_from_fork = fork ();
		if (ret_from_fork == 0)  // child process
		{
		//	close (1);
			dup2 (pipe_fd[1], 1);
			execlp ("cat", "cat", "dup.c", NULL);
		}
		else
		{
		//	close (0);
			dup2 (pipe_fd[0], 0);
			close (pipe_fd[1]);
			execlp ("grep", "grep", "include", NULL);
		}
	}
	return 0;
}

2、执行结果
在这里插入图片描述


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值