Advertisement
YellowAfterlife

Unix, creating and stopping processes

May 4th, 2012
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. /*
  2. Задание: обработка сигналов SIGQUIT, SIGINT, SIGTTIN.
  3. Сборка:
  4. gcc one.c -o one.out
  5. gcc two.c -o two.out
  6. ./two.out
  7. */
  8. /// two.c:
  9. // includes:
  10. #include <stdlib.h> // exit(code)
  11. #include <stdio.h>  // printf(...), scanf(...)
  12. #include <unistd.h> // execl()
  13. #include <signal.h> // sig, kill, ...
  14.  
  15. int main(int agrc, char *argv[]) {
  16.     int code, input; // return code, input number
  17.     pid_t pid; // process id of child process
  18.     // display sort of menu:
  19.     printf("What will you do?\n");
  20.     printf("1 - SIGQUIT (end process 'on its own')\n");
  21.     printf("2 - SIGINT (end process)\n");
  22.     printf("3 - SIGTTIN (stop process)\n");
  23.     scanf("%i", &input);
  24.     pid = fork(); // fork process
  25.     switch (pid) { // do depending on result of fork
  26.     case -1: // fork fail
  27.         printf(" ~ Failed to fork");
  28.         exit(1);
  29.         break;
  30.     case 0: // child process:
  31.         if ((execl("one.out", "1", NULL)) == -1) break;
  32.         // Error in execl.
  33.         perror("\n ~ Error in execl()");
  34.         printf("\n ~ Did you try 'gcc one.c -o one.out'?");
  35.         exit(1);
  36.     default: // parent process:
  37.         switch(input) { // send code depending on input
  38.         case 1:
  39.             kill(pid, SIGQUIT);
  40.             break;
  41.         case 2:
  42.             kill(pid, SIGINT);
  43.             break;
  44.         case 3:
  45.             kill(pid, SIGTTIN);
  46.             break;
  47.         }
  48.         wait(&code); // wait until child process finishes
  49.         switch (code) { // display text depending on returned code:
  50.         case SIGQUIT:
  51.             printf("Process ended by SIGQUIT.");
  52.             break;
  53.         case SIGINT:
  54.             printf("Process ended by SIGINT.");
  55.             break;
  56.         default:
  57.             printf("Process ended.");
  58.         }
  59.         printf(" Returned code %d\n", code);
  60.         break;
  61.     }
  62. }
  63. /// one.c:
  64. #include <stdlib.h>
  65. #include <stdio.h>
  66. #include <signal.h>
  67. // procedure to make process end 'by itself':
  68. void do_exit() {
  69.     exit(1);
  70. }
  71.  
  72. int main(int agrc, char *argv[])
  73. {
  74.     struct sigaction sa;
  75.     sigset_t signal_set;
  76.     // try to set signal
  77.     if(signal(SIGTTIN, do_exit) < 0) {
  78.         perror("Error setting signal");
  79.     }
  80.     for(;;) { // wait until stopped by host.
  81.         sleep(1);
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement