ashok13123 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks, My code is like this $pid=fork(); exec("notepad"); $SIG{INT}=\&handler; sub handler { kill 1,$pid; } when i execute this code,it will open the notepad.What i want is if i am pressing CTRL+C, in the signal handler,it should close the notepad application. Can anyone help me out????Thanks in advance

Replies are listed 'Best First'.
Re: closing notepad using perl
by gone2015 (Deacon) on Dec 10, 2008 at 19:21 UTC

    You say your code "like" this:

    $pid=fork(); exec("notepad"); $SIG{INT}=\&handler; sub handler { kill 1,$pid; }
    ...I would expect an if (or something similar) to do the exec in the child and the rest in the parent... surely ?

    So I tried:

    my $pid = fork() ; die "fork failed '$!'" if !defined($pid) ; if ($pid == 0) { exec("notepad") ; } ; print "Started Notepad \$pid = $pid\n" ; my $r = 1 ; sub handler { kill 'INT', $pid ; $r = 0 ; } ; $SIG{INT}=\&handler; while ($r) { sleep(1) } ; print "And we're done\n" ;
    and I discovered (on ActivePerl 5.10.0) that: (a) the $pid returned was -ve, and related to a thread within the perl process; and (b) that the $pid was not the pid of the notepad process. I imagine I should have known that.

    I could not find a way of discovering the pid of the process created by the exec -- and system doesn't do the trick either....

    But I did find Win32::Process, and the following appears to work:

    use strict ; use warnings ; use Win32::Process ; use Win32 ; my $SystemRoot = $ENV{SystemRoot} ; print "\$SystemRoot = '$SystemRoot'\n" ; sub ErrorReport{ print Win32::FormatMessage( Win32::GetLastError() ); } my $ProcessObj ; Win32::Process::Create($ProcessObj, "$SystemRoot\\notepad.exe", "notepad", 0, NORMAL_PRIORITY_CLASS, "." ) or die ErrorReport() ; my $pid = $ProcessObj->GetProcessID() ; print "Started Notepad \$pid = $pid\n" ; my $run = 1 ; sub handler { $ProcessObj->Kill(1234) ; $run = 0 ; } ; $SIG{INT}=\&handler; while ($run) { sleep(1) } ; print "And we're done\n" ;
    ... so I've learned something today :-) But I'm not sure if this is what you wanted (in particular I've assumed that the reference to "notepad" means you're running Windows....

Re: closing notepad using perl
by Anonymous Monk on Dec 10, 2008 at 10:06 UTC
    Use system instead of exec.
        i tried system,but it is not closing the notepad.Whether i have to make any changes in the kill statement?