Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight

Re: Interesting behaviour with signals and threads

by marioroy (Parson)
on Oct 07, 2019 at 16:42 UTC ( #11107139=note: print w/replies, xml ) Need Help??

in reply to Interesting behaviour with signals and threads

Hi, shulam

Ah, the woes with signal handling :)

use 5.20.2; use warnings; use threads; use Time::HiRes qw/ time usleep /; $SIG{USR2} = 'IGNORE'; $SIG{TERM} = 'IGNORE'; my $pid; if (($pid = fork()) == 0) { sleep 1; my $ppid = getppid(); for (1 .. 1000) { usleep(int(rand(100000))); kill 'USR2', $ppid; kill 'TERM', $ppid; } } my $main_thr = threads->self(); $SIG{TERM} = sub { say "TERM"; }; $SIG{USR2} = sub { say "USR2"; }; my $thread = threads->create(sub { # Depending on implementation, the thread may receive the signal. # One way is to relay the signal to the intended recepient. $SIG{TERM} = $SIG{USR2} = sub { $main_thr->kill($_[0]); }; # Sleep stops early upon receiving a signal. my $start = time; do { usleep 1000; } until (time - $start >= 10.0); threads->exit(); }); # Wait for thread to finish. while ($thread->is_running()) { usleep 1000; } # Reap thread. $thread->join(); # Ditto, reap child. kill('KILL', $pid); waitpid($pid, 0);

Regards, Mario

Replies are listed 'Best First'.
Re^2: Interesting behaviour with signals and threads
by shulam (Novice) on Oct 09, 2019 at 09:20 UTC

    Thanks for the reply and the code!

    I was thinking of doing something like making a thread handler and the main process handler do the same thing regardless of which actually received the signal, but your solution seems a lot cleaner than what I had in mind.

    In the end I removed the thread, though. It seems that mixing all this stuff together makes the program run in a weird way and I think I might get less complications in the future by just removing the thread.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11107139]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2020-09-27 01:27 GMT
Find Nodes?
    Voting Booth?
    If at first I donít succeed, I Ö

    Results (142 votes). Check out past polls.