How do you make Perl properly kill a subprocess?

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

    When you register, my team of editors will also send you resources covering Linux administration and management; integration and interoperability between Linux, Windows and Unix; securing Linux and mixed-platform environments; and migrating to Linux.

    Margie Semilof, Editorial Director

    By submitting your registration information to SearchEnterpriseLinux.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchEnterpriseLinux.com is governed by our Terms of Use. You may contact us at webmaster@TechTarget.com.

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