in reply to Doing every X seconds

This looks more like a perlfork requirement to me, although we need to check child alive without wait. Example:
use POSIX ":sys_wait_h"; my $child = fork; if ($child) { # parent case my $res; while (not ($res = waitpid($child, WNOHANG))) { sleep 5; # check file list here # ... } if ($res == -1) { warn "fatal child error\n"; exit; } } else { # child case # insert job processing here exit; # child must explicitly exit otherwise both would continue e +xecuting this } # reach here if job processing completed successfully
(code updated)

One world, one people

Replies are listed 'Best First'.
Re^2: Doing every X seconds
by mr_mischief (Monsignor) on Aug 06, 2018 at 23:00 UTC

    You forgot to check the definedness of $child, as upon failure to fork you'll get undef. You likely do not want to pretend you're supposed to be executing the child case code in that circumstance.

    I'm puzzled by "# child must explicitly exit otherwise both would continue executing this". The wording suggests both parent and child will continue executing the child case which of course is untrue. As written, the child would fall out of the else clause and the parent's waitpid would still see the child's exit status if that call to exit were not present. You then say to "# reach here if job processing completed successfully" which in your case only the parent will and the child won't because of the above-mentioned exit. Perhaps it would be clearer for the first one to say "... or the child will continue past the else block and we only want the parent to do so" or something similar.

    If the intent is for both programs to be done after the branch, a shared exit just after the entire if statement could be useful. Any code you intend for the parent only to run after the child is gone could be placed in the parent's case in the if block, after the loop on waitpid. It's also possible to have the parent exit and the child continue, and that's desirable under certain circumstances.

    At this point I think it's worth mentioning there are tools to do this handling for you. Depending on your exact needs, there are Parallel::ForkManager, AnyEvent::ForkManager, IPC::Run, IPC::Run3, Proc::Fork, Proc::Fork::Control, Proc::Daemon, and a whole lot more.

    A reply falls below the community's threshold of quality. You may see it by logging in.