日期:2014-05-16 浏览次数:20870 次
#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;
}