How to handle execvp(…) errors after fork()?

后端 未结 6 1417
孤街浪徒
孤街浪徒 2020-12-08 08:45

I do the regular thing:

  • fork()
  • execvp(cmd, ) in child

If execvp fails because no cmd is found, how can I notice this error in parent pr

6条回答
  •  忘掉有多难
    2020-12-08 09:14

    You terminate the child (by calling _exit()) and then the parent can notice this (through e.g. waitpid()). For instance, your child could exit with an exit status of -1 to indicate failure to exec. One caveat with this is that it is impossible to tell from your parent whether the child in its original state (i.e. before exec) returned -1 or if it was the newly executed process.

    As suggested in the comments below, using an "unusual" return code would be appropiate to make it easier to distinguish between your specific error and one from the exec()'ed program. Common ones are 1, 2, 3 etc. while higher numbers 99, 100, etc. are more unusual. You should keep your numbers below 255 (unsigned) or 127 (signed) to increase portability.

    Since waitpid blocks your application (or rather, the thread calling it) you will either need to put it on a background thread or use the signalling mechanism in POSIX to get information about child process termination. See the SIGCHLD signal and the sigaction function to hook up a listener.

    You could also do some error checking before forking, such as making sure the executable exists.

    If you use something like Glib, there are utility functions to do this, and they come with pretty good error reporting. Take a look at the "spawning processes" section of the manual.

提交回复
热议问题