[net.unix-wizards] strange behaviour with background process.

lars@myab.UUCP (lars) (07/23/85)

I am running on SVR2 and tried to make the following program to work. It
almost works (prints done every 10'th second), but whenever I press the
interrupt key to stop some program, the interrupt is caught by this
program. If I press the 'quit' key, a core is dumped.

I even tried the following: run 'sh', start the program, stop the
'sh' and the hit the 'intr' key. It was caught !

Is this a bug or a feature ?


The program:

#include <signal.h>

int interr();

main() {
    if (fork()) return;
    signal(SIGINT, interr);
    while (1) {
	sleep(10);
	printf("done\n");
    }
}

interr() {
    signal(SIGINT, interr);
    printf("int\n");
}
-- 
    ______________________________________________________
	Lars Pensjo
	{decvax,philabs}!mcvax!enea!chalmers!myab!lars

guy@sun.uucp (Guy Harris) (07/28/85)

> I am running on SVR2 and tried to make the following program to work.
> ...whenever I press the interrupt key to stop some program, the interrupt
> is caught by this program. ...
> 
> Is this a bug or a feature ?
> 
> The program: ...

> main() {
>     if (fork()) return;
>     signal(SIGINT, interr);
>     while (1) {
> 	sleep(10);
> 	printf("done\n");
>     }
> }

A feature.  You told your program to catch the interrupt signal; why the
surprise when it does?  Running something in the background does not
disconnect it from the terminal, unless you're running with a shell that
supports job control (like the 4.xBSD C shell, the Gwyn/Natalie-modified
Bourne shell, or the Korn shell).  Processes run in the background are not
affected by keyboard-generated interrupt (or quit) signals because the shell
ignores those signals before running the program, not because those signals
aren't sent to the process.

The correct code is:

	int (*oldsig)();

	oldsig = signal(SIGINT, SIG_IGN);
	if (oldsig != SIG_IGN)
		signal(SIGINT, interr);

This code first tests whether SIGINT is being ignored, by getting the
current value of the signal.  If it is not being ignored, it then catches
it.  If this program is run in the foreground, SIGINT will not be ignored
and it will catch it.  If it is run in the background, SIGINT will be
ignored and it will leave it that way.

	Guy Harris