R – How to make a time counter as child process that works in parallel to program


How can I make a live time counter that ticks on the screen in parallel to part of a working program?

let's say I have the following little sub code which run an internal program for a couple of minutes:

system (`compile command`);
exec "simu -sh"; 

While waiting it to end, can I open a fork or something that output to stdout a running clock time?

Another question may be, how can I output to screen the ALARM counter without hurt the rest of the script?

Best Solution

It is important to give context to your question. You already have two processes: a parent and a child. The child is replacing itself with the exec, so you can't use the child to do any form of monitoring, but the parent is available. We just need to make the waitpid call non-blocking (i.e. it won't wait to be successful, it will fail right away). This also gets rid of the need for the eval and alarm functions:


use strict;
use warnings;
use POSIX ":sys_wait_h";

my $timeout = 180;
my $program = "simulator --shell";

die "could not fork: $!" unless defined (my $pid = fork);

#this is the child process
unless ($pid) {
    exec $program;
    #if we reach this code the exec failed
    die "exec of simulator failed: $!";

#this is the parent process
my $tries = 0;
#check to see if $pid is done, but don't block if it isn't
until (waitpid(-1, WNOHANG) == $pid) {
    #put what you want to print while waiting here:
    print scalar localtime, "\n";

    if ($tries++ > $timeout) {
        warn "timed out, sending SIGKILL to simulator\n";
        kill 9, $pid;
        waitpid($pid, 0);
} continue {
    sleep 1;
Related Question