source: liacs/os/assignment3/assignment3.c@ 191

Last change on this file since 191 was 2, checked in by Rick van der Zwet, 15 years ago

Initial import of data of old repository ('data') worth keeping (e.g. tracking
means of URL access statistics)

File size: 2.0 KB
RevLine 
[2]1/****************************
2* March 5, 2008 *
3* Operating Systems *
4* LIACS *
5* Spring Semester 2008 *
6* Assignment #3 *
7* Written by Sjoerd Henstra *
8****************************/
9
10#include <stdlib.h>
11#include <stdio.h>
12#include <signal.h>
13#include <errno.h>
14#include <string.h>
15#include <unistd.h>
16
17// printerror prints a custom error message followed by the error code and
18// description to stderr
19void printerror(const char* message) {
20 fprintf(stderr, "%s\nERROR %i: %s\n", message, errno, strerror(errno));
21}
22
23// signal handler, handles SIGUSR1 and SIGUSR2 properly
24static void handler(int signal) {
25 int pid = getpid();
26 switch(signal) {
27 case SIGUSR1:
28 printf("process %i received SIGUSR1\n", pid);
29 break;
30 case SIGUSR2:
31 printf("process %i received SIGUSR2\n", pid);
32 break;
33 default:
34 printf("process %i caught another signal, this shouldn't happen\n", pid);
35 break;
36 }
37}
38
39int main() {
40 int parent_pid; // holds parent process id, used by child to signal parent
41 int child_pid; // hold child process id, used by parent to signal child
42 int status;
43
44 // set signal handlers for signals SIGUSR1 and SIGUSR2
45 if (signal(SIGUSR1, handler) == SIG_ERR) {
46 printerror("Cannot set handler for SIGUSR1.");
47 }
48 if (signal(SIGUSR2, handler) == SIG_ERR) {
49 printerror("Cannot set handler for SIGUSR2.");
50 }
51
52 parent_pid = getpid();
53 printf("parent pid: %i\n", parent_pid);
54
55 // split into parent and child
56 if ((child_pid = fork()) == 0) {
57 printf("child pid: %i\n", getpid());
58
59 // send signal to parent
60 kill(parent_pid, SIGUSR1);
61
62 sleep(1); // LINE 51 <--------
63
64 printf("child is done\n");
65
66 } else {
67 // send signals to child
68 kill(child_pid, SIGUSR1);
69 kill(child_pid, SIGUSR2); // LINE 59 <---------
70
71 sleep(1); // LINE 61 <---------
72
73 printf("parent is done\n");
74
75 // reap child
76 wait(&status);
77 printf("child reaped\n");
78 }
79 return 0;
80}
Note: See TracBrowser for help on using the repository browser.