The Linux Programming Interface

(nextflipdebug5) #1
Process Groups, Sessions, and Job Control 713

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

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

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

parentPid = getpid();
printf("PID of parent process is: %ld\n", (long) parentPid);
printf("Foreground process group ID is: %ld\n",
(long) tcgetpgrp(STDIN_FILENO));

w for (j = 1; j < argc; j++) { / Create child processes /
childPid = fork();
if (childPid == -1)
errExit("fork");


if (childPid == 0) { / If child... /
e if (argv[j][0] == 'd') / 'd' --> to different pgrp /
if (setpgid(0, 0) == -1)
errExit("setpgid");


sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
sa.sa_handler = handler;
r if (sigaction(SIGHUP, &sa, NULL) == -1)
errExit("sigaction");
break; / Child exits loop /
}
}


/* All processes fall through to here */

t alarm(60); / Ensure each process eventually terminates /


y printf("PID=%ld PGID=%ld\n", (long) getpid(), (long) getpgrp());
for (;;)
u pause(); / Wait for signals /
}
–––––––––––––––––––––––––––––––––––––––––––––––––––––– pgsjc/disc_SIGHUP.c
Suppose that we run the program in Listing 34-4 in a terminal window with the fol-
lowing command:


$ exec ./disc_SIGHUP d s s > sig.log 2>&1

The exec command is a shell built-in command that causes the shell to do an exec(),
replacing itself with the named program. Since the shell was the controlling pro-
cess for the terminal, our program is now the controlling process and will receive
Free download pdf