c - handling sigusr1 and sigusr2, works for only sigusr2 -


this (almost) homework question. have sender , receiver program. sender takes pid of receiver , int t command line parameters. has string consists of , bs(e.g. "aabbba") , sends string receiver via signals. every in string sends sigusr1 , every b sends sigusr2. , waits t milliseconds between every letter.

receiver, should print every sigusr1 , b every sigusr2 arrived. can't understand why receiver prints bs. that's first problem.

in code above, use 2 signal handlers, 1 each. want know if it's possibile use single handler handle both of them. read it's not ok. i'm not sure if got true. tried both of them anyway prints bs. ok use handler this?:

 void handler(int signum)  {     if (signum == sigusr1) // arrived .     {       write(1,"a\n", 2);     }     else if(signum == sigusr2) //arrived _:     {       write(1,"b\n", 2);     }  }   //in main function...   sa.sa_handler = handler_sg1;  ec_neg1(sigaction(sigusr1, &sa, null), "sigaction");  ec_neg1(sigaction(sigusr2, &sa, null), "sigaction"); 

sender.c :

 #include <stdio.h>  #include <stdlib.h>  #include <errno.h>  #include <time.h>  #include <signal.h>   #define ec_neg1(s,m) if((s) == -1) {perror(m); exit(errno);}    int main(int argc, char *argv[])  {   pid_t pid;   int sleepval;    struct timespec ts;    if(argc == 3)   {     pid = atoi(argv[1]);     sleepval= atoi(argv[2]);      ts.tv_sec = 0;     ts.tv_nsec = sleepval * 1000000l;      printf("sender started...\n");      char msg[100] = "aabbbaba";     int i;      (i = 0; msg[i] != '\0'; ++i)     {           if(msg[i] == 'a')               kill(pid, sigusr1);           else if( msg[i] == 'b')               kill(pid, sigusr2);            //wait sleepval  milliseconds after every signal           ec_neg1(nanosleep(&ts, null),"nanosleep failed")     }      printf("done.\n");    }    return 0;  }  

receiver.c :

 #include <stdio.h>  #include <stdlib.h>  #include <string.h>  #include <errno.h>  #include <unistd.h>  #include <signal.h>   #define ec_neg1(s,m) if((s) == -1) {perror(m); exit(errno);}     static void handler_sg1(int signum)  {     write(1,"a\n", 2);  }   static void handler_sg2(int signum)  {     write(1,"b\n", 2);  }   int main(int argc, char *argv[])  {     struct sigaction sa;     memset(&sa, 0, sizeof(sa));    sa.sa_handler = handler_sg1;    ec_neg1(sigaction(sigusr1, &sa, null), "sigaction");    sa.sa_handler = handler_sg2;    ec_neg1(sigaction(sigusr2, &sa, null), "sigaction");     printf("receiver started...\n");     while(1)      ;     return 0;  } 

ok. if assign sleepval tv_sec , have tv_nsec assigned 0 work ?


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -