How to get return value from CHILD PROCESS?
TLDR
int wstatus;
waitpid(<pid>, &wstatus, 0); // Store proc info into wstatus
int return_value = WEXITSTATUS(wstatus); // Extract return value from wstatus
Reference
The manpage for waitpid
shows its type signature is:
pid_t waitpid(pid_t pid, int *stat_loc, int options);
It also states that we can store process information with the stat_loc
argument:
if the value of the argument
stat_loc
is not a null pointer, information shall be stored in the location pointed to bystat_loc
the
stat_val
argument is the integer value pointed to bystat_loc
.
We then use WEXITSTATUS(wstatus)
to extract our return value from the process.
WEXITSTATUS(
stat_val
): If the value of WIFEXITED(stat_val) is non-zero, this macro evaluates to the low-order 8 bits of the status argument that the child process passed to _exit() or exit(), or the value the child process returned from main().
Oops! This isn't bash! Anyway...
The reason for spawning a process is to continue the main flow, doing something meanwhile that doesn't affect that. I'm running through directories of 10k images, & moving out duplicates. I put the compare code in a function & subprocess that. It's very fast.
The way to get a value back is to create a pipe, echo a value onto that then read the pipe: ( Warning! the following code probably doesn't work, it just shows a working pipe)
mkfifo pipe
moved=0
# Use imageMagick 'compare' to find files with zero difference:
comPare () {
if [[ ! $(compare -metric AE $1 $2) ]]; then
mv $2 moved;
echo 1 > pipe;
else echo 0 > pipe
fi
}
# For every file in the dir, compare it to every other one:
for file1 in $( ls *.bmp | head -n $(( $( ls *.bmp | wc -l) - 1)); do
for file2 in $( ls *.bmp | tail -n $(( $( ls *.bmp | wc -l) - 1)); do
comPare file1 file2 &
moved=$(( $(cat pipe) + 1 ))
done
done
rm pipe
echo "Moved $moved files"
The only problem so far is that I'm working on a usb drive, & permissions are stopping me from creating the pipe. Apart from that ...
What you are looking for is wait() or waitpid().
Like dtmilano said you should use wait or waitpid, depending or need.
But maybe you should split your program in two parts and execute the son with exec. When you make fork your child process receive pid equal 0 and I don't know if you try to wait signals of process with pid 0 will work fine.
Anyway you can pass, though it's not the best way, the value calculated by your child process through exit.