我正试图在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);
}
}