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;
}

Guess you like

Origin blog.csdn.net/m0_48788975/article/details/121587983