Linux管道读写问题
是不是如果读进程不读走管道缓冲区中的数据,那么写操作将一直阻塞?我写了段代码,结果好像不大一样,请教下是我代码的问题还是对这个理解错误。代码如下
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int nPipeFd[2] = {0};
int nRet = 0;
char cBuff = '0';
pid_t pid = 0;
nRet = pipe(nPipeFd);
if(0 == nRet)//Creat PIPE Successfully
{
pid = fork();
if(pid > 0)//Parent Progress:write PIPE
{
while(1)
{
nRet = write(nPipeFd[1], &cBuff, 1);
if(-1 == nRet)
{
printf("Write PIPE Failed\n");
break;
}
printf("The Data Write PIPE is %c\n", cBuff);
cBuff++;
if('5' == cBuff)
{
cBuff = '0';
}
sleep(2);//Write 1 Byte to PIPE per. 2 Second
}
return 1;
}
else//Child Progress:read PIPE and Print the data to Screen
{
while(1)
{
sleep(10);
nRet = read(nPipeFd[0], &cBuff, 1);
if(0 == nRet)
{
printf("Nothing to read in PIPE");
}
else
{
printf("The Data Read From PIPE is %c\n", cBuff);
}
sleep(2);//Read 1 Byte to PIPE per. 2 Second
}
return 2;
}
}
else
{
printf("Sorry Creat PIPE Failed\n");
}
return 0;
}
if(-1 == nRet)就阻塞了,直到子进程的10s延迟到后去读数据才继续往下走。但是实际的效果确实会每隔2s左右就打印"The Data Write PIPE is X",这是怎么回事?谢谢! 管道?
{
printf("Write PIPE Failed\n");
break;
}