So I have a program which creates a child process and executes a command (for example, ls). The parent will then use pipes to send to and get from the child. This works fine when I’m inputting commands myself from the command line.
However, when the input comes from a file, it seems like the child doesn’t have enough time to run and I get NULL when reading from the pipe – even though there will be information coming from it.
Short of using sleep(), is there a better way to make sure the child has run before trying to read from it?
Thanks a lot!
If your haven’t set your pipe file descriptor as non-blocking, then there should be no problem. Any read on the pipe will block until the child produces output; if you need to be responsive to multiple file descriptors (for example, standard input from the user and the pipe from the child process), use
select()orpoll().I assume it is
fgets()that is returning NULL. That indicates either end-of-file (meaning that the child has closed its end of the pipe), or an error. You can check which of these is true usingfeof()orferror(). Useperror()in the error case to see what the error actually is.