简体   繁体   English

从管道打印到屏幕值时输出错误

[英]Wrong output when printing to screen values from a pipe

I am trying to get the hang of pipes in UNIX and I am writing a simple program that is supposed to generate 10 random numbers and output one of them on the screen every second. 我试图摆脱UNIX中管道的困扰,并且正在编写一个简单的程序,该程序应该生成10个随机数,并每秒在屏幕上输出其中一个。 The parent process is the one that generate and passes such numbers to the child via pipe and the child gets the values and handles the displaying. 父进程是生成此类数字并通过管道将其传递给子进程的进程,子进程将获取值并处理显示。 (Aside the timing issue) My problem is if I output the numbers with printf() the program works as it is supposed to, but if I try to write on STDOUT_FILENO then I get a bunch of nasty symbols... and I can't figure out why. (除了计时问题)我的问题是,如果我用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);
    }
}

When you use printf() , it converts binary numbers to human-readable representation (ie an ASCII string representing a number). 当您使用printf() ,它将二进制数字转换为人类可读的表示形式(即表示数字的ASCII字符串)。 When you use write() , it simply writes binary data. 使用write() ,它仅写入二进制数据。 Writing binary data to a terminal is never a good idea. 将二进制数据写入终端绝不是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM