首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

Linux管道读写有关问题

2013-04-02 
Linux管道读写问题是不是如果读进程不读走管道缓冲区中的数据,那么写操作将一直阻塞?我写了段代码,结果好

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)
{
printf("Write PIPE Failed\n");
break;
}
就阻塞了,直到子进程的10s延迟到后去读数据才继续往下走。但是实际的效果确实会每隔2s左右就打印"The Data Write PIPE is X",这是怎么回事?谢谢! 管道?
[解决办法]
匿名管道阻塞只会在管道写满的时候发生,你每次都有读,不会阻塞,你理解错啦

热点排行