// Sample signal() program (man signal) and (man sigaction) // Creates two children process, both of which will print their PID and do some work // The parent will just do some work and then send a signal to the children to kill // themselves (horrible isn't it?) #include #include #include #include #include // NEW!!! #define NCHILDS (2) void signal_handler(int s) { printf("Signal handler.\n"); if (s == SIGUSR1) { printf("Child %d - signal SIGUSR1 raised.\n", getpid()); } else if (s == SIGUSR2) { printf("Child %d - signal SIGUSR2 raise.\n", getpid()); printf("killing child\n"); exit(0); } fflush(NULL); return; } int main(int argc, char** argv) { int childpid[NCHILDS]; int i; int j; int fChild = 0; // flag if its a child proc or not struct sigaction sa; int p_pid, p_sig, p_sig2; printf("Sample fork() program.\n"); printf("Parent's PID is %d\n", getpid()); printf("Forking...\n"); for (i = 0; i < NCHILDS; i++) { childpid[i] = fork(); // Get out of the loop if it's a child process if (childpid[i] == 0) { fChild = 1; break; } } if (fChild == 1) { /* child proc */ /* NEW - install a signal handler so the parent can use it */ sa.sa_handler = signal_handler; sa.sa_flags = 0; // attach signal handler to the process // when the signal SIGUSR1 is raised, we'll do something if (sigaction(SIGUSR1, &sa, NULL) == -1) { printf("Something broke.\n"); return 0; } if (sigaction(SIGUSR2, &sa, NULL) == -1) { printf("Something broke.\n"); return 0; } printf("Child born - PID = %d\n", getpid()); for (j = 0; j < 100000000; j++) { //printf("Child %d goes to sleep.\n", getpid()); //printf("Child %d wakes up.\n", getpid()); rand(); sleep(1); } } else { /* parent */ sleep(2); // Make sure the childs are created first. printf("Parent's two children are %d %d\n", childpid[0], childpid[1]); do { printf("Enter a child's pid and a 1 or 2 (i.e. 220 1)\n"); printf("Control-c to end.\n"); scanf("%d %d", &p_pid, &p_sig); p_sig2 = (p_sig == 1) ? SIGUSR1 : SIGUSR2; if (kill(p_pid, p_sig2) == -1) // man kill -- sends the signal { printf("kill() didn't work.\n"); } } while (1); } return 0; }