how to correctly wait for execve to finish?

前端 未结 4 781
甜味超标
甜味超标 2021-01-14 15:31

A C source code (compiled and running Linux Centos 6.3) has the line:

execve(cmd, argv, envp);

execve does not return, but I w

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 15:54

    Here's one possibility.

    dash does, in fact, need to know when a child process terminates. It must reap the child (by waiting it) to avoid filling the process table with zombies, and anyway it cares about the exit status of the process.

    Now, it knows what the PID of the process it started was, and it can use that when it does a wait to figure out which process terminated and therefore what to do with the exit status.

    But you are doing an extra fork. So dash thinks it started some process with PID, say, 368. But you fork a new child, say PID 723. Then you wait for that child, but you ignore the status code. Finally, your process terminates successfully. So then dash notices that process 368 terminated successfully. Even if it didn't.

    Now suppose dash was actually executing a script like

    do_something && do_something_else
    

    The programmer has specified that the shell definitely shouldn't do_something_else if do_something failed. Terrible things could happen. Or at least mysterious things. Yet, you have hidden that failure. So dash cheerfully fires up do_something_else. Et voilà

    Well, it's just a theory. I have no idea, really, but it shows the sort of thing that can happen.

    The bottom line is that dash has some mechanism which lets it know when child processes have finished, and if you want to hook into the exit handling of a child process, you'd be much better off figuring out how that mechanism works so that you can hook into it. Trying to add your own additional mechanism is almost certain to end in tears.

提交回复
热议问题