c - How to make two processes signalling each others continuously? -


i want simulate game server should continuously send , receive signals parent. scenario follows:

  • parent sends signal game.
  • game catches signal , sends signal parent.
  • parent catches signal , sends again signal game.

and on...

the problem stops receiving or sending after first lap:

static int game_s; void game() {        printf("game\n");     signal(sigusr1,game);     sleep(1);     kill(getppid(),sigusr1);     pause(); } void parent() {     printf("parent\n");     signal(sigusr1,parent);     sleep(1);     kill(game_s,sigusr1);     pause(); } void main() {      game_s = fork();     if(game_s>0)     {                signal(sigusr1,parent);         sleep(1);         kill(game_s,sigusr1);         pause();     }     else     {         signal(sigusr1,game);         pause();     } } 

the output following:

game parent 

why stopped here? shouldn't game server catch parent's signal , print "game" again...

by default reception of specific signal blocked moment process received specific signal until related signal handler had been left.

from man 3 signal:

void (*signal(int sig, void (*func)(int)))(int); 

[...]

when signal occurs, , func points function, implementation-defined whether equivalent of a:

         signal(sig, sig_dfl); 

is executed or implementation prevents implementation-defined set of signals (at least including sig) occurring until current signal handling has completed.

to change behaviour establish signal handling via sigaction() instead of signal() (which 1 should ways portability reasons).

sigaction() takes struct sigaction. member sa_flags of latter should have sa_nodefer set.

from linux' man 2 sigaction:

sa_nodefer

do not prevent signal being received within own signal handler. flag meaningful when establishing signal handler.

posix words differently:

sa_nodefer

if set , sig caught, sig shall not added thread's signal mask on entry signal handler unless included in sa_mask. otherwise, sig shall added thread's signal mask on entry signal handler.


be aware each signal handler gets it's own stack allocated each time gets invoked, sooner or later recursive ping-pong ends in out-of-memory condition.


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -