Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

How to pass CTRL-C to child script only

by ohmysea (Novice)
on Aug 23, 2010 at 13:37 UTC ( [id://856704] : perlquestion . print w/replies, xml ) Need Help??

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


I have perl scripts A and B, where script B is called by script A. When I run script A, which will then initiate script B, I want to be able to press CTRL-C and have it terminate script B only, with script A continuing to run from after it called B.

I tried using $SIG{'INT'} handlers but both scripts always get terminated together. Is the above situation possible? How can it be accomplished?


Replies are listed 'Best First'.
Re: How to pass CTRL-C to child script only
by MidLifeXis (Monsignor) on Aug 23, 2010 at 13:59 UTC


    Did you set A to ignore and B to handle the signal? Please show some code, so that the monastery can help you find the problem.

    Update: As stated below, you will probably need to, after forking, set the process group and/or pass along the signal from A to B.


      Yes, I've tried that:

      Script A:
      $SIG{'INT'} = 'IGNORE';

      Script B:
      $SIG{'INT'} = sub { exit(0); };

      With this, CTRL-C has no effect on either script.
      Using die instead of exit has the same result.

      Also, script B is called from script A as follows:
      my $login = new CQLogin(); $login->autoLogon();
      autoLogon is a subroutine in script B (CQLogin)

        In script A do:
        $SIG{INT} = sub { kill 2, $pid_of_scriptB;};

        Should work, not tested.

        This is still unclear, reason is, do you  fork in CQLogin? If you don't you're just  useing the module invoking a method on the instantiated object within the same process and the whole process will just terminate on Ctrl-C

Re: How to pass CTRL-C to child script only
by JavaFan (Canon) on Aug 23, 2010 at 15:10 UTC
    The control-C is a request for the shell to send SIGINT to the program it has running on the foreground. Which is script A. Probably the easiest is (either from another shell, or after you've put script A in the background) kill -2 PID where PID is the process ID of script B.
Re: How to pass CTRL-C to child script only
by salva (Canon) on Aug 23, 2010 at 17:06 UTC
    Try calling setpgrp in the child process just after forking it.