代码示例:

#include <stdio.h>

#include <unistd.h>

#include <fcntl.h>

#define READ_TERMINAL 0

#define WRITE_TERMINAL 1

int main() {

int file_descriptors;

pid_t pid_f;

char PipeBuf={‘a’,‘0’};

int read_ret=0;

pipe(file_descriptors);

pid_f=fork();

if (pid_f<0)

{

printf(“fork error!n”);

exit(1);

}

else if (pid_f==0)

{

//子进程向父进程发一则消息

printf(“Write in Pipe To FatherProcess!n”);

close(file_descriptors);

sleep(1);

write(file_descriptors,“Child Send”,sizeof(“Child Send”));

//open(file_descriptors);

}

else

{

//父进程接收(读取)消息

printf(“Read in Pipe From ChildProcess!n”);

//通过fcntl()修改为使得读管道数据具有非阻塞的特性

int flag=fcntl(file_descriptors,F_GETFL,0);

flag |= O_NONBLOCK;

if(fcntl(file_descriptors,F_SETFL,flag) < 0){

perror(“fcntl”);

exit(1);

}

close(file_descriptors);

read_ret=read(file_descriptors,PipeBuf,sizeof(PipeBuf));//没阻塞的读

printf(“Read Message are : %sn”,PipeBuf);

编制一段程序,实现进程间的管道通信。使用系统调用pipe()建立一条管道,两个子进程p1和p2分别向通道各写一句话:
The first child process is sending message!
The second child process is sending message!
而父进程则从管道中读出来自两个进程的信息,显示在屏幕上。
示例
int fd;
char outpipe,inpipe;
pipe(fd); , /*创建一个管道*/
write(fd,outpipe,100); , /*向管道写长为100字节的串*/
read(fd,inpipe,100); , /*从管道中读长为100字节的串*/
互斥访问管道
锁管道:lockf(fd, 1, 0)
管道解锁:lockf(fd, 0, 0)