5.2 PIPE编程实例

1、实验代码
pipe.c

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

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

int main (int argc, char *argv[])
{
	int pipe_fd[2]; 
	if (pipe (pipe_fd) == -1) 
        handle_error("pipe");

	int ret_from_fork;
	ret_from_fork = fork ();
	if (ret_from_fork == -1)
        handle_error("fork");

	if (ret_from_fork == 0)   //child process
	{
		char str[100] = {0}; 
		printf("child process:\n input string:");
		scanf ("%s", str);
		//gets(str);
		write (pipe_fd[1], str, strlen (str)); // write data to pipe
		close (pipe_fd[1]);
		_exit (EXIT_SUCCESS);
	}

	if (ret_from_fork > 0)   // parent process
	{
		char buf[30] = {0};
		read (pipe_fd[0], buf, 30); // read data from pipe
		printf ("parent process: %s\n", buf);
		close (pipe_fd[0]);
		exit (EXIT_SUCCESS);
	}

	return 0;
}

pipe-v2.c

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

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

int main (int argc, char *argv[])
{
	int pipe_fd1[2]; 
	int pipe_fd2[2]; 
	if (pipe (pipe_fd1) == -1 || pipe (pipe_fd2) == -1) 
        handle_error("pipe");

	int ret_from_fork;
	ret_from_fork = fork ();
	if (ret_from_fork == -1)
        handle_error("fork");
	if (ret_from_fork == 0)   //child process
	{
		char read_buf1[100] = {0}; 
		char write_buf1[100] = {0}; 
		printf("child process:");
		scanf ("%s", write_buf1);
		//gets(str);
		write (pipe_fd1[1], write_buf1, strlen (write_buf1));
		close (pipe_fd1[1]);

		//sleep(5);
		read (pipe_fd2[0], read_buf1, 100);
		printf ("in child process: %s\n", read_buf1);
		close (pipe_fd2[0]);
		_exit (EXIT_SUCCESS);
	}

	if (ret_from_fork > 0)   // parent process
	{
		char read_buf2[100] = {0};
		char write_buf2[100] = {0};
		read (pipe_fd1[0], read_buf2, 100); // read data from pipe
		printf ("in parent process: %s\n", read_buf2);
		close (pipe_fd1[0]);

		printf ("parent process:");
		scanf ("%s", write_buf2);
		write (pipe_fd2[1], write_buf2, strlen (write_buf2));
		close (pipe_fd2[1]);
		exit (EXIT_SUCCESS);
	}

	return 0;
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值