1
votes

I got a problem. Trying to write a simple programm which forks once

The parent proccess sends child bytes from /dev/urandom and child outputs them to screen (15 bytes in HEX per line). The problem is: when i first open the compiled programm the output looks like:

B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 ... B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0 B0

(not always "B0", but surely the same ONE byte) When I run the same program (not re-compiled) once again the output seems to be OK... Any ideas ?

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>





int main(int argc, char *argv[])
{

        char bufforek[256];

        printf("P1: READING /dev/urandom\n");

        FILE *file_ptr = fopen("/dev/urandom", "r");


        int file=open("FIFO",O_RDWR);
        mkfifo("FIFO",0666);
        char pomoc;
        int hexa;
        int i=1;


        if(fork()==0)
        {

            char bufforek1[256];
            while(read(file,bufforek1,sizeof(bufforek1)))
            {

                pomoc = *bufforek1;
                // printf("%hhX ", pom);

                hexa = (int)pomoc;
                pomoc = *bufforek1;
                printf("%hhX ", pomoc);
                if(i==15)
                {
                    printf("\n");
                    i=1;
                }
                else i++;
                // write(pipe_table[1],bufforek,sizeof(bufforek));

            }
            return 0;
        }
        while ((fgets(bufforek, sizeof(bufforek), file_ptr))!=NULL) write(file, bufforek, sizeof(bufforek));

        unlink("FIFO");


    return 0;
}
1
A couple of issues... why are you creating the fifo mkfifo() after opening it? And you are not checking the number of bytes read from each of the fds...rodrigo

1 Answers

0
votes

As rodrigo points out, your instructions mkfifo and open("FIFO"...) are backwards, also if you are going to use a temporary fifo, you can simply use pipe(2) call rather than creating and deleting a fifo.