简体   繁体   English

等待执行可执行脚本的子进程

[英]Waitpid for a child process that execv an unexecutable script

I am doing the following steps in my code: 我在代码中执行以下步骤:

  • fork()
  • execv in the child process to run an external script 子进程中的execv运行外部脚本
  • in the parent process: 在父进程中:

 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; 我面临的问题是,如果脚本不可执行,我仍然会在上述while循环中结束,并且我发出信号,表明脚本已启动且没有错误; 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? 显然,我可以运行sys调用并事先确定脚本的权限,但是有更好的解决方案吗?

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. 正是由于以下原因,捕获execve错误非常棘手:该错误在子进程中可见,但您希望将其转移到父进程中。 There's a nice trick to make it possible: 有一个很好的技巧使之成为可能:

  1. 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). 在分叉之前,打开pipe并设置close-on-exec标志(使用pipe2O_CLOEXEC ;如果系统上不存在前者,则设置为fcntl )。

  2. After forking, have the parent close the writing side of the pipe and read from the reading end. 分叉后,让父级关闭管道的书写侧并从读取端读取。

  3. In the child, close the reading end of the pipe, and attempt execve . 在孩子,关闭管道的读出端,并尝试execve If it fails, write errno to the pipe and _exit . 如果失败, errno写入管道和_exit

  4. In the parent, if read returns 0, execve was successful. 在父级中,如果read返回0,则execve成功。 This is because a successful execve closes the pipe (because it's set for close-on-exec) and causes EOF on the reading end. 这是因为成功的execve关闭了管道(因为它被设置为close-on-exec)并在读取端导致EOF。 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. 让孩子在执行脚本后继续执行exit(2)或其他某个值,并在父循环中测试退出值。 But why the loop? 但是为什么循环呢? Just get rid of WNOHANG. 只是摆脱WNOHANG。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM