[英]Wrong output when printing to screen values from a pipe
我试图摆脱UNIX中管道的困扰,并且正在编写一个简单的程序,该程序应该生成10个随机数,并每秒在屏幕上输出其中一个。 父进程是生成此类数字并通过管道将其传递给子进程的进程,子进程将获取值并处理显示。 (除了计时问题)我的问题是,如果我用printf()
输出数字,程序将按预期方式工作,但是如果我尝试在STDOUT_FILENO
上写,那么我会得到一堆讨厌的符号...找出原因。
if ( pid > 0 ) { //If I am the parent...
close( fd[0] );
srand( time ( NULL ) ); //throw the seed for random numbers...
for (i = 0; i < 10; i++)
{
sleep(1); //Waiting one second...
r = rand() % 100; //getting the number...
//As long as numbers are generated, put them on the pipe...
if ( ( write (fd[1], &r, sizeof(r) ) ) < 0 ) {
perror( "Error write()" );
exit( 1 );
}
}
}
else
{ //I am the child...
close (fd[1]);
//as long as there's something on the pipe, read it...
while ((read_bytes = read(fd[0], &buf, sizeof(buf))) > 0 ) {
//and shout it out on screen!
write(STDOUT_FILENO, &buf, read_bytes);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.