16. Inter-process communications: signals

Already known: pipes

Signals

Already known: terminal keyboard input (C, Z, ^\)

Signal is:

Example simple never-end program:

   1 #include <stdio.h>
   2 #include <unistd.h>
   3 
   4 int main(int argc, char *argv[]) {
   5         int i;
   6         for(i=0;; i++) {
   7                 sleep(1);
   8                 printf("%d\n", i);
   9         }
  10         return 0;
  11 }

kill utility — send a signal to a process

BTW:

It's just a convention, both types runs by fork()/exec()

So:

Sending and catching signals

Base article: GeeksforGeeks

Send a signal: kill

   1 #include <stdio.h>
   2 #include <sys/types.h>
   3 #include <signal.h>
   4 #include <stdlib.h>
   5 
   6 int main(int argc, char *argv[]) {
   7         if(kill(atoi(argv[1]), atoi(argv[2])))
   8                 perror("Can't kill");
   9         return 0;
  10 }

Handler (signal):

   1 #include <stdio.h> 
   2 #include <unistd.h>
   3 #include <signal.h> 
   4   
   5 void handler(int sig) { 
   6     printf("Caught %d\n", sig); 
   7 } 
   8   
   9 int main(int argc, char *argv[]) {
  10     signal(SIGINT, handler); 
  11     signal(SIGSEGV, handler); 
  12     int i;
  13     for(i=0;; i++) {
  14       sleep(1);
  15       printf("%d\n", i);
  16     }
  17     return 0; 
  18 }

Looking after child process:

   1 #include <stdio.h>
   2 #include <wait.h>
   3 #include <signal.h>
   4 #include <unistd.h>
   5 
   6 int main(int argc, char *argv[]) {
   7     int stat;
   8     pid_t pid;
   9     if ((pid = fork()) == 0)
  10         while(1) ;
  11     else
  12     {
  13         printf("Forking a child: %d\n", pid);
  14         wait(&stat);
  15         printf("And finally…\n");
  16         if (WIFSIGNALED(stat))
  17             psignal(WTERMSIG(stat), "Terminated:");
  18         printf("Exit status: %d\n", stat);
  19     }
  20         return 0;
  21 }

H/W

TODO

HSE/ProgrammingOS/16_IPC (последним исправлял пользователь NataliaKrauze 2020-03-23 20:04:15)