Your parent thread needs to wait until the child is ready before it tries to read from the pipe. There are a couple of ways to do this.
First, you can use a condition variable. Declare a variable that both threads can access and set it to 0
. Your child thread will set it to 1
when is is ready for the parent to read. The parent will wait until the variable changes to 1
(using something like while(!condvar) sleep(1);
), then it will read from the pipe and reset the variable to 0
so that the child knows that the parent is finished.
Another option is to use a form of inter-process communication, such as signals. Similar to the condition variable method, the child thread will perform its work and then send a signal to the parent thread when it is done. The parent thread will wait until it receives the signal before it reads from the pipe, and then it can send a signal back to the child indicating that it is done.
Edit: Since you're spawning the child process with fork
instead of with threads, you can't use a condition variable here (parent and child will have separate copies of it).
Instead, you can use the signal()
and kill()
functions to send signals between the processes. Before forking, use getpid
to store a copy of the parent's pid (for the child process). Also store the return value of fork
, since it will contain the child's pid.
To send a signal to the other process, use something like:
kill(parent_pid, SIGUSR1);
The receiving process needs to set up a signal handler. For example:
int signal_received = 0;
void signal_handler(int signal_num) {
if (signal_num == SIGUSR1)
signal_received = 1;
}
signal(SIGUSR1, signal_handler);
The function signal_handler
now will be automatically called whenever the process receives signal number SIGUSR1
. Your thread would wait in a loop, watching for this variable to change using something like:
while (1) { // Signal processing loop
// Wait here for a signal to come in
while (!signal_received) { sleep(1); }
// Wake up and do something
read_from_pipe();
...
signal_received = 0;
}