The answer of @DanielPorteous should work too if you don't want to use thread in your program.
The idea is simple, not keeping the waitpid
and the read
function to wait unless they consumes some time to do their operation. The idea is keeping a timeout mechanism so that, if waitpid
has nothing to create an impact to the whole operation, it will return immediately and the same thing goes for the read operation too.
If the read
function takes very long time to read the whole buffer, you may restrict the reading manually from the read
function so that it doesn't read the whole at once, rather it reads for 2 milliseconds and then pass the cycle to the waitpid
function to execute.
But its safe to use threading for your purpose and its pretty easy to implement. Here's a nice guideline about how can you implement threading.
In your case you need to declare two threads.
pthread_t readThread;
pthread_t waitpidThread;
Now you need to create the thread and pass specific function as their parameter.
pthread_create(&(waitpidThread), NULL, &waitpidFunc, NULL);
pthread_create(&(readThread), NULL, &readFunc, NULL);
Now you may have to write your waitpidFunc
and readFunc
function. They might look like this.
void* waitpidFunc(void *arg)
{
while(true) {
pid_t pid = waitpid(...);
// This is to put an exit condition somewhere.
// So that you can finish the thread
int exit = process_waitpid_event(...);
if(exit == 0) break;
}
return NULL;
}