Possible Duplicate:
Child process receives parent’s SIGINT
the is my code in below
The function is after the father receive the signal of CTRL-C. the father process send signal to son1 and son2; after the son1 and son2 exit, the father process exit;
but the result does not like that; this is the answer
son1
son2
^Cheeell
the son1 id 5963
the son2 id 5964
Parent process is killed !!
who can help me, thank you before!!
#include <stdio.h>
#include <sys/signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#define SIGNAL_TO_SON1 10
#define SIGNAL_TO_SON2 12
#define FLAG_MSG_NO 0
#define FLAG_MSG_YES 1
int parent_msg = FLAG_MSG_NO;
void signal_sendToParent( int sig )
{
printf("heeell\n");
parent_msg = FLAG_MSG_YES;
}
int son1_flag = FLAG_MSG_NO;
void signal_handle_son1( int sig )
{
printf("handle_son1\n");
son1_flag = FLAG_MSG_YES;
}
int son2_flag = FLAG_MSG_NO;
void signal_handle_son2( int sig )
{
printf("handle_son2\n");
son2_flag = FLAG_MSG_YES;
}
int main( void )
{
int pid1, pid2;
if ( ( pid1 = fork() ) < 0 )
{
printf("erro!!!!");
return -1;
}
if ( pid1 > 0 )
{
// in the parent
while( ( pid2 = fork() ) == -1);
if ( pid2 == 0 )
{
signal( SIGNAL_TO_SON2, signal_handle_son2 );
printf("son2\n");
// in the son2;
while ( son2_flag != FLAG_MSG_YES );
{
printf("Child process 2 is killed by parent !!\n");
exit(0);
}
}else{
// setup the signal
signal( SIGINT, signal_sendToParent );
while ( parent_msg != FLAG_MSG_YES );
{
kill( pid1, SIGNAL_TO_SON1 );
kill( pid2, SIGNAL_TO_SON2 );
wait(0);
printf("the son1 id %d\n", pid1 );
printf("the son2 id %d\n", pid2 );
wait(0);
int status , pid ;
while( ( pid = waitpid( -1, &status, 0 ) ) > 0 )
{
printf("child %d \n", pid );
}
printf("Parent process is killed !!\n");
exit(0);
}
}
}else{
// in the son1;
printf("son1\n");
signal( SIGNAL_TO_SON1, signal_handle_son1 );
while ( son1_flag != FLAG_MSG_YES );
{
printf("Child process 1 is killed by parent !!\n");
exit(0);
}
}
return 0;
}