Linux 匿名管道





#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
int main()
{
	int pipe_fd[2];
	if (pipe(pipe_fd) < 0)//pipe函数用于创建管道,如果小于0,失败
	{
		perror("pipe\n");//perror打印错误信息
		return 1;
	}
	pid_t id = fork();//创建子进程
	if (id < 0)//<0表明出错返回
	{
		perror("fork\n");
		return -1;
	}
	//子进程。创建子进程后,子进程返回0,父进程返回子进程id
	else if (id == 0)
	{
		close(pipe_fd[0]);//child关闭读--向匿名管道中写入数据
		const char* msg = "i am a child\n";
		int count = 5;
		int i = 0;
		while (1)
		{
			write(pipe_fd[1], msg, strlen(msg));
			if (count-- == 0)
				break;

			sleep(1);
			printf("child: write data: %d\n", i++);
		}
		close(pipe_fd[1]);
	}
	else
	{//父进程从匿名管道中读数据
		close(pipe_fd[1]);//pipe_fd[1]为写数据--关闭写端
		char buf[1024];
		int count = 5;
		while (1)
		{
			memset(buf, '\0', sizeof(buf));//每次进行初始化
			ssize_t _s = read(pipe_fd[0], buf, sizeof(buf)-1);//读数据
			if (_s > 0)//返回值大于0,读取成功,打印
			{
				printf("client ->server:%s\n", buf);
			}
			else if (_s == 0)//等于0,说明结束
			{
				printf("read pipe EOF...\n");
			}
			else//小于0 出错 直接退出循环
				break;
		}
	}

	close(pipe_fd[0]);
	int status = 0;
	pid_t ret = waitpid(id, &status, 0);//waitpid进程等待函数
	if (ret == id)//ret==id 说明等待成功
	{
		printf("wait child sucess...\n");
		printf("get sig:%d\n", status & 0xff);
		printf("exit code :%d\n", (status >> 8) & 0xff);

	}
	return 0;
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值