The Linux Programming Interface

(nextflipdebug5) #1

728 Chapter 34


process group becoming orphaned, the signal handler is invoked, and it displays
the child’s process ID and the signal number q.

Listing 34-7: SIGHUP and orphaned process groups
––––––––––––––––––––––––––––––––––––––––––––––– pgsjc/orphaned_pgrp_SIGHUP.c
#define _GNU_SOURCE /* Get declaration of strsignal() from <string.h> */
#include <string.h>
#include <signal.h>
#include "tlpi_hdr.h"

static void /* Signal handler */
handler(int sig)
{
q printf("PID=%ld: caught signal %d (%s)\n", (long) getpid(),
sig, strsignal(sig)); /* UNSAFE (see Section 21.1.2) */
}

int
main(int argc, char *argv[])
{
int j;
struct sigaction sa;

if (argc < 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s {s|p} ...\n", argv[0]);

setbuf(stdout, NULL); /* Make stdout unbuffered */

sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
w if (sigaction(SIGHUP, &sa, NULL) == -1)
errExit("sigaction");
if (sigaction(SIGCONT, &sa, NULL) == -1)
errExit("sigaction");

printf("parent: PID=%ld, PPID=%ld, PGID=%ld, SID=%ld\n",
(long) getpid(), (long) getppid(),
(long) getpgrp(), (long) getsid(0));

/* Create one child for each command-line argument */

e for (j = 1; j < argc; j++) {
switch (fork()) {
case -1:
errExit("fork");

case 0: /* Child */
printf("child: PID=%ld, PPID=%ld, PGID=%ld, SID=%ld\n",
(long) getpid(), (long) getppid(),
(long) getpgrp(), (long) getsid(0));

if (argv[j][0] == 's') { /* Stop via signal */
printf("PID=%ld stopping\n", (long) getpid());
Free download pdf