I have a program that uses fork()
to create a child process. I have seen various examples that use wait()
to wait for the child process to end before closing, but I am wondering what I can do to simply check if the file process is still running.
I basically have an infinite loop and I want to do something like:
if(child process has ended) break;
How could I go about doing this?
EDIT: If you just want to know if the child process stopped running, then the other answers are probably better. Mine is more to do with synchronizing when a process could do several computations, without necessarily terminating.
If you have some object representing the child computation, add a method such as
bool isFinished()
which would return true if the child has finished. Have a private bool member in the object that represents whether the operation has finished. Finally, have another method privatesetFinished(bool)
on the same object that your child process calls when it finishes its computation.Now the most important thing is mutex locks. Make sure you have a per-object mutex that you lock every time you try to access any members, including inside the
bool isFinished()
andsetFinished(bool)
methods.EDIT2: (some OO clarifications)
Since I was asked to explain how this could be done with OO, I'll give a few suggestions, although it heavily depends on the overall problem, so take this with a mound of salt. Having most of the program written in C style, with one object floating around is inconsistent.
As a simple example you could have a class called
ChildComputation
Now in your main program, where you fork:
Hope that makes sense.
To reiterate, what I have written above is an ugly amalgamation of C and C++ (not in terms of syntax, but style/design), and is just there to give you a glimpse of synchronization with OO, in your context.
Use
waitpid()
with theWNOHANG
option.You don't need to wait for a child until you get the
SIGCHLD
signal. If you've gotten that signal, you can callwait
and see if it's the child process you're looking for. If you haven't gotten the signal, the child is still running.Obviously, if you need to do nothing unitl the child finishes, just call
wait
.