linux无名管道实验代码,linux无名管道

本文详细介绍了Unix/Linux系统中用于进程间通信的pipe()和pipe2()函数。通过创建一个无方向的数据通道,这两个函数允许数据在不同进程中传递。pipe()返回两个文件描述符,分别对应管道的读端和写端。在示例程序中,父进程与子进程通过管道进行数据交换,子进程接收用户输入并写入管道,而父进程则从管道读取并打印数据。
摘要由CSDN通过智能技术生成

#include

#include

#include

#if 0

int pipe(int pipefd[2]);

#define _GNU_SOURCE /* See feature_test_macros(7) */

#include

int pipe2(int pipefd[2], int flags);

DESCRIPTION

pipe() creates a pipe, a unidirectional data channel that can be used

for interprocess communication. The array pipefd is used to return two

file descriptors referring to the ends of the pipe. pipefd[0] refers

to the read end of the pipe. pipefd[1] refers to the write end of the

pipe. Data written to the write end of the pipe is buffered by the

kernel until it is read from the read end of the pipe. For further

details, see pipe(7).

#endif

int main(int argc ,char*argv[])

{

int buf[1024];

int len;

int pip[2],rc,c;

int *readfd;

int *writefd;

readfd=&pip[0];

writefd=&pip[1];

rc = pipe(pip);

printf("start\n");

if(rc == -1)

{

printf("\ncreat pipe fail \n");

}

rc = fork();

switch(rc)

{

case -1:

printf("fork err \n");

exit(1);

case 0:

close(*readfd);

while( (c =getchar())>0)

{

write(*writefd,&c,1);

}

break;

default:

close(*writefd);

while(read(*readfd,&c,1)>0)

{

putchar(c);

}

break;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值