1、编制实现管道通信的程序。使用系统调用 pipe()函数建立一条管道线,两个子进程分别向管道各写一句话。Child process 1 is sending a message

管道创建函数

创建管道可以通过调用 pipe()来实现,表1列出了pipe()函数的语法要点。

表1 pipe()函数语法要点

所需头文件

#include <unistd.h>

函数原型

int pipe(int fd[2])

函数传入值

fd[2]:管道的两个文件描述符,pipe之后就可以直接操作这两个文件描述符

返回值

成功:0

出错:-1

 

 

例子:编制实现管道通信的程序。
使用系统调用 pipe()函数建立一条管道线,两个子进程分别向管道各写一句话。
Child process 1 is sending a message!
Child process 2 is sending a message! 

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
int main(){
int fd[3],pid1,pid2;
char OutPipe[100],InPipe[100];
pipe(fd);
while((pid1=fork())==-1);
if(pid1==0){
lockf(fd[1],1,0);
sprintf(OutPipe,"Child process 2 is sending a message!");
write(fd[1],OutPipe,50);
sleep(1);
lockf(fd[1],0,0);
exit(0);
}
else{
while((pid2=fork())==-1);
if(pid2==0){
lockf(fd[1],1,0);
sprintf(OutPipe,"Child process 1 is sending a message!");
write(fd[1],OutPipe,50);
sleep(1);
lockf(fd[1],0,0);
exit(0);}
else{
read(fd[0],InPipe,50);
printf("%s\n",InPipe);
wait(0);
read(fd[0],InPipe,50);
printf("%s\n",InPipe);
exit(0);
}
}
return 0;
}

  • 15
    点赞
  • 105
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值