这是我在下面的代码
功能是 父亲收到CTRL-C的信号后。 父进程向son1和son2发送信号; 在son1和son2退出之后,父进程退出;
但结果不是那样的; 这就是答案
son1
son2
^Cheeell
the son1 id 5963
the son2 id 5964
Parent process is killed !!
谁可以帮助我,谢谢你!!
#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;
}
答案 0 :(得分:1)
得到你想要的东西你必须忽略孩子们的SIGINT。
请参阅此What happens to a SIGINT (^C) when sent to a perl script containing children?
简而言之,Ctrl-C将发送到前台组中的所有进程。 这意味着您的子进程也会获得SIGINT,它们没有处理程序并被杀死。
signal( SIGINT, SIG_IGN );
添加子代码,接近设置其他信号处理程序。