我正在尝试掌握 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);
}
}