16 comment

  1. You can also do it with bash using sleep and job control:
    $ foo & sleep 10 && kill %1 && fg

  2. Good one, I have to download and use it. Thanks.

    The tip from Professor Fapsanders is also useful, we can make it more significant to kill the last background process by this:

    $ sh foo & sleep 5 && kill $! && fg

    // Jadu, unstableme.blogspot.com

  3. Warning: the tip from Professor Fapsanders only works if “foo” does not require any input (background processes cannot do that).

    For the general case, you need to background the alarm process instead, as the sample “timeout” script does.

    1. $ sh foo & sleep 5 && kill $! & fg ### (note the last “&” is not “&&”, so you foreground the job immediately)

  4. How can i suppress the stupid ‘alarm clock’ output when the timeout expires?
    I’m running “perl -e ‘alarm shift @ARGV; exec @ARGV’ 5 cat” it terminates the cat command after 4 seconds but then i get stupid ‘Alarm clock’ output on the screen. I have to use this command in a shell script and i don’t want this output.

    I have tried redirecting standard error and std out but if i specify >/dev/null at the end of cat command, it redirects ‘cat”s output not from perl -e….. Any ideas? Thanks a lot

    1. even m facing the error, in the code below

      #include
      #include
      #include
      using namespace std;
      void onAlarm(int a)
      {
      cout<<"Alarm Buzzz\n";
      sleep(2);
      exit(0);
      }
      int main()
      {
      signal(SIGALRM, onAlarm);
      cout<<"enter\n";
      alarm(3);
      execl("./sant/a.out","./a.out",(char*)0);
      }

      if the file a.out has a sleep of say 10 seconds
      then it wont execute the onAlarm() function, instead it would just show Alarm clock
      can u help?

  5. Thanks Peter.

    But the problem is appending >/dev/null 2>&1 to the command redirects stdout and stderr for the “command” not for the perl. So even by appending this to the command i still get “Alarm Clock” after command terminates.

    For example perl -e ‘alarm shift @ARGV; exec @ARGV’ 5 foo arg1 arg2 > /dev/null 2>&1 ‘ will redirect output and stderr from ‘foo’ command not from the alarm command.
    Thanks

  6. hey, you’re right… that’s funny.
    I tried to dig some deeper using strace and funnily it does not show up then:

    strace perl -e “alarm shift @ARGV; exec @ARGV” 5 cat >/dev/null 2>&1

    interesting issue, I do lack enough time to investigate
    regards

  7. Thanks. Using the perl snippet is neat. Pretty much all UNIX systems come with bash and perl. So, this is cool.

Comments are closed.