linux signal question

Programming, for all ages and all languages.
Post Reply
sancho1980
Member
Member
Posts: 199
Joined: Fri Jul 13, 2007 6:37 am
Location: Stuttgart/Germany
Contact:

linux signal question

Post 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
User avatar
JamesM
Member
Member
Posts: 2935
Joined: Tue Jul 10, 2007 5:27 am
Location: York, United Kingdom
Contact:

Re: linux signal question

Post by JamesM »

Yes, I can.

You have a local and a global variable, both called 'child'. You work the rest out ;)
sancho1980
Member
Member
Posts: 199
Joined: Fri Jul 13, 2007 6:37 am
Location: Stuttgart/Germany
Contact:

Re: linux signal question

Post 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?
User avatar
JamesM
Member
Member
Posts: 2935
Joined: Tue Jul 10, 2007 5:27 am
Location: York, United Kingdom
Contact:

Re: linux signal question

Post 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).
Post Reply