Ask the Expert

How do you make Perl properly kill a subprocess?

How do you make perl properly kill a subprocess? I use:

$chiproc=fork();
if ($chiproc==0) { system("runsomething"); }
if ($chiproc!=0) { sleep(10); kill 9,$chiproc; }

This kills the forked process, but it does nothing to "runsomething" that it created.

    Requires Free Membership to View

You're detecting the cloned process correctly, but the system() call creates a third process, which I don't think you mean to do. What you want to do is replace the program in the cloned process (that's the second copy of the perl interpreter running your script) with your "runsomething" program.

To do that just use exec() instead of system(). It overwrites the current process with a new program. It's documented in the perlfunc(1) manual page, and in exec(2). fork() and exec() used as a pair in this way is a very common idiom.

This was first published in June 2004

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: