I am doing the following steps in my code:
fork()
execv
in the child process to run an external script While( waitpid(..., WNOHANG) == 0)
{
//Send signal that script has started with no error
..
}
The problem I am facing is that if the script is not executable I still end up in the above while loop and I send the signal that script has started with no errors; which is not true.
Obviously I can run a sys call and determine the permission of the script before hand, but is there a better solution?
Catching execve
errors is tricky for exactly the reason you've found: the error is seen in the child process but you want to transfer it to the parent process. There's a nice trick to make it possible:
Before forking, open a pipe
and set the close-on-exec flags (with pipe2
and O_CLOEXEC
, or fcntl
if the former is not available on your system).
After forking, have the parent close the writing side of the pipe and read from the reading end.
In the child, close the reading end of the pipe, and attempt execve
. If it fails, write errno
to the pipe and _exit
.
In the parent, if read
returns 0, execve
was successful. This is because a successful execve
closes the pipe (because it's set for close-on-exec) and causes EOF on the reading end. Otherwise the value read is the error code.
Have the child do exit(2) or some other value if it is still there after it execs the script, and test the exit value inside your parent loop. But why the loop? Just get rid of WNOHANG.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.