linux无名管道实验代码,Linux 进程间通讯之创建无名管道和读写无名管道

Linux进程间通讯的方式:

1. 管道(pipe)和有名管道(FIFO).

2. 信号(signal)

3. 消息队列

4. 共享内存

5. 信号量

6. 套接字(socket)

管道通讯:

无名管道:由pipe()函数创建,int pipe(int  filedis[2]), 当管道建立时有两个文件描述符,filedis[0]用于读管道,filedis[1]用于写管道。关闭管道,仅需将两个文件描述符关闭即可。

创建无名管道pipe():

#include

#include

int main(){

intpipe_filed[2];

if(pipe(pipe_filed)<0){

printf("pipecreate failed.\n");

return-1;

}

else{

printf("pipecreate successfully.\n");

close(pipe_filed[0]);                            //关闭相应读管道(必须要)

close(pipe_filed[1]);                            //关闭相应写管道(必须要)

}

}

注:fork()必须在pipe()之前来创建子进程,否则子进程无法进程相应的文件描述符,如果在fork之后,那么fork会在子/父进程各执行一次,属不同的管道。

读写无名管道示例:

#include

#include

#include

#include

int main(){

charcache[100];

intfiledis[2];

if(pipe(filedis)< 0){

printf("Createpipe failed.\n");

return-1;

}

memset(cache,0, sizeof(cache));            //在一段内存块中填充某个特定的值,此为,对cache数组以0进行填充

intpid;

pid= fork();                                            // 创建子进程

if(pid== 0){                                            //    进入子进程

printf("Inchild process.\n");

close(filedis[1]);                          //    关闭写管道

sleep(3);                                        //    等待,为了等父进程写入东西

read(filedis[0],cache, 100);    //    读管道,并将内容写入cache之中

printf("%s.\n",cache);              //    打印cache内容

close(filedis[0]);                          //    关闭读管道

}

elseif(pid > 0){                            //    进入父进程

printf("Inparent process.\n");

close(filedis[0]);                          //    关闭读管道

write(filedis[1],"Hello ",6);    //    第一次写入

write(filedis[1],"linuxdba", 8);        //    第二次写入

close(filedis[1]);                          //    关闭写管道

wait(NULL);                                  //    等待子进程退出再往下执行

}

else{

printf("Createchild process failed.\n");

return-1;

}

return0;

}0b1331709591d260c1c78e86d0c51c18.png

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值