简体   繁体   中英

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. 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.

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). When you use write() , it simply writes binary data. Writing binary data to a terminal is never a good idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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