代碼示例:
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
#defineREAD_TERMINAL0
#defineWRITE_TERMINAL1
intmain(){
intfile_descriptors[2];
pid_tpid_f;
charPipeBuf[64]={‘a(chǎn)’,‘0’};
intread_ret=0;
pipe(file_descriptors);
pid_f=fork();
if(pid_f<0)
{
printf(“forkerror!\n”);
exit(1);
}
elseif(pid_f==0)
{
//子進(jìn)程向父進(jìn)程發(fā)一則消息
printf(“WriteinPipeToFatherProcess!\n”);
close(file_descriptors[READ_TERMINAL]);
sleep(1);
write(file_descriptors[WRITE_TERMINAL],“ChildSend”,sizeof(“ChildSend”));
//open(file_descriptors[READ_TERMINAL]);
}
else
{
//父進(jìn)程接收(讀取)消息
printf(“ReadinPipeFromChildProcess!\n”);
//通過fcntl()修改為使得讀管道數(shù)據(jù)具有非阻塞的特性
intflag=fcntl(file_descriptors[READ_TERMINAL],F_GETFL,0);
flag|=O_NONBLOCK;
if(fcntl(file_descriptors[READ_TERMINAL],F_SETFL,flag)<0){
perror(“fcntl”);
exit(1);
}
close(file_descriptors[WRITE_TERMINAL]);
read_ret=read(file_descriptors[READ_TERMINAL],PipeBuf,sizeof(PipeBuf));//沒阻塞的讀
printf(“ReadMessageare:%s\n”,PipeBuf);