mukesh
mukesh

Reputation: 716

Waiting for input from a file descriptor

I am redirecting the file descriptors for stdin and stdout in the child process as follows. Now i want the child process to wait until the data is available at the input descriptor. Currently if data is not available at the input descriptor then the child process takes some random value ( i guess EOF ) and terminates.

fd0=open("in1.dat", O_RDWR|O_CREAT);
fd1=open("out1.dat", O_RDWR|O_CREAT);
if(pid==0)
    {
    dup2(fd0, 0); // redirect input to the file
    dup2(fd1, 1); // redirect output to the file
    execlp("./flip","flip","new","4",NULL);
}

Upvotes: 1

Views: 919

Answers (1)

William Pursell
William Pursell

Reputation: 212198

Reading from a file descriptor will block until data is available (unless you arrange for the read to be non-blocking). In your case, if the file is empty, then a read will indeed return 0 to indicate end of file and write nothing into the buffer (so the random value you are seeing there is whatever was there before you called read). If you are wanting to treat the input file as a pipe (eg, you want the child to wait until someone else writes data to the file) then you want to make the input file a fifo rather than a regular file. (eg, use mknod instead of open.)

Upvotes: 4

Related Questions