Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- 8. SIGPIPE, SIGUSR2, SIGTTOU. В родительском процессе установить обработчик SIGCHLD и распечатать причину отправки сигнала SIGCHLD (si_code).
- Сборка:
- gcc one.c -o one.out
- gcc two.c -o two.out
- ./two.out
- */
- /// one.c:
- #include <stdlib.h>
- #include <stdio.h>
- #include <signal.h>
- // procedure to make process end 'by itself':
- void do_exit() {
- exit(1);
- }
- int main(int agrc, char *argv[])
- {
- if(signal(SIGPIPE, do_exit) < 0) {
- perror("Error setting signal");
- }
- for(;;) { // wait until stopped by host.
- sleep(1);
- }
- }
- /// two.c:
- // includes:
- #include <stdlib.h> // exit(code)
- #include <stdio.h> // printf(...), scanf(...)
- #include <unistd.h> // execl()
- #include <signal.h> // sig, kill, ...
- // Signal handler for SIGCHLD
- void sighandler_child(int sig) {
- printf("SIGCHLD Signal: %d\n", sig);
- /* not sure what else can be done here */
- }
- int main(int agrc, char *argv[]) {
- int code, input; // return code, input number
- pid_t pid; // process id of child process
- // display sort of menu:
- printf("What will you do?\n");
- printf("1 - SIGPIPE (end process 'on its own')\n");
- printf("2 - SIGUSR2 (end process)\n");
- printf("3 - SIGTTOU (end process by keyboard)\n");
- scanf("%i", &input);
- pid = fork(); // fork process
- switch (pid) { // do depending on result of fork
- case -1: // fork fail
- printf(" ~ Failed to fork");
- exit(1);
- case 0: // child process:
- if ((execl("one.out", "1", NULL)) == -1) break;
- // Error in execl.
- perror("\n ~ Error in execl()");
- printf("\n ~ Did you try 'gcc one.c -o one.out'?");
- exit(1);
- default: // parent process:
- // set SIGCHLD handler:
- signal(SIGCHLD, sighandler_child);
- switch(input) { // send ending code depending on input
- case 1: kill(pid, SIGPIPE); break;
- case 2: kill(pid, SIGUSR1); break;
- case 3: kill(pid, SIGTTOU); break;
- }
- wait(&code); // wait until child process finishes
- switch (code) { // display text depending on returned code:
- case SIGPIPE: printf("Process ended by SIGSEGV."); break;
- case SIGUSR2: printf("Process ended by SIGTERM."); break;
- case SIGTTOU: printf("Process ended by SIGTSTP."); break;
- default: printf("Process ended.");
- }
- printf("Returned code %d\n", code);
- break;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement