Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I disable END blocks in child processes?

Tags:

fork

perl

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 } }

?

like image 389
mob Avatar asked Nov 29 '10 19:11

mob


People also ask

What does waitpid() do?

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.

What does Waitpid 1 mean?

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.

How do I know if my Waitpid is successful?

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.

What are Office child processes?

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.


1 Answers

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 }
like image 186
cjm Avatar answered Oct 06 '22 22:10

cjm