Page 1 of 1

linux signal question

Posted: Fri Jun 12, 2009 2:59 pm
by sancho1980
hi

please look at the following piece of code

Code: Select all

pid_t child = 0;

void forward(int signum)
{
	if (child != 0) {
		printf("sig in parent\n");
	} else {
		printf("sig in child\n");
	}
}

int main(int argc, char *argv[])
{
	for(;;) {
		pid_t child = fork();
		if (child < 0) exit(1);
		if (child == 0) {
			argv[0] = "ping";
			execvp("ping", argv);
		}
		signal(SIGINT, &forward);
		int status;
		wait(&status);
		printf("child %d dead :-( respawning...\n", child);
	}
}
i don't understand the signalling-logic behind this: when i run this, i can see the child on my console output the ping stuff
when i press ctrl-c, i get the output:
sig in child
why?

the signal handler was installed only AFTER the fork and only within the parent's address space.
can any of you make sense of that?

thanks

martin

Re: linux signal question

Posted: Fri Jun 12, 2009 5:06 pm
by JamesM
Yes, I can.

You have a local and a global variable, both called 'child'. You work the rest out ;)

Re: linux signal question

Posted: Fri Jun 12, 2009 5:18 pm
by sancho1980
damn i didnt see that
so the handler is really executed in the parent space
but then i can go on to my next question: if the SIGINT handler is executed in the parent space, how come that the child exits as soon as the parent receives sigint?

is it that the child receives sigint as well, and then dies, because it has no handler?
do all children receive the same signals as their parent?
or whats the story with signals in parent-child relationships?

Re: linux signal question

Posted: Sat Jun 13, 2009 4:59 am
by JamesM
I'm not sure of the posixness of it - I don't know whether the signal gets sent to the entire process group or all processes having your terminal as their controlling tty.

Either way, the parent and child are grouped together and both receive the signal. The default behaviour for SIGINT is to exit(1).