-1

可能重复:
子进程收到父进程的 SIGINT

下面是我的代码

作用是在父收到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;
}
4

1 回答 1

1

要得到你想要的,你必须忽略孩子们的 SIGINT。

看到这个当发送到包含孩子的 perl 脚本时,SIGINT (^C) 会发生什么?

简而言之,Ctrl-C 被发送到前台组中的所有进程。这意味着您的子进程也会获得 SIGINT,它们没有处理程序并被杀死。

signal( SIGINT, SIG_IGN );

添加子代码,靠近设置其他信号处理程序。

于 2013-01-02T17:48:21.557 回答