I frequently use fork
in programs that also have END { ... }
blocks:
...
END { &some_cleanup_code }
...
my $pid = fork();
if (defined($pid) && $pid==0) {
&run_child_code;
exit 0;
}
The child process executes the END {}
block as it is exiting, but usually I don't want that to happen. Is there a way to prevent a child process from calling the END
block at exit? Barring that, is there a way for a program to "know" that it is a child process, so I could say something like
END { unless (i_am_a_child_process()) { &some_cleanup_code } }
?
The waitpid() function allows the calling thread to obtain status information for one of its child processes. The calling thread suspends processing until status information is available for the specified child process, if the options argument is 0.
From the linux manual : The pid parameter specifies the set of child processes for which to wait. If pid is -1, the call waits for any child process.
If successful, waitpid() returns a value of the process (usually a child) whose status information has been obtained. If WNOHANG was given, and if there is at least one process (usually a child) whose status information is not available, waitpid() returns 0.
A child process is a process that is created by another process, called the parent process. For more information, see the following topics: Creating Processes.
I don't think there's any way to prevent END blocks from running in a forked process, but this should let you detect it:
my $original_pid; BEGIN { $original_pid = $$ }
... # Program goes here
END { do_cleanup() if $$ == $original_pid }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With