CTRL + C和CTRL + Z信号在C中不会被阻止

时间:2016-03-14 18:57:17

标签: c unix pipe signals signal-handling

我在C中为一个简单的3人游戏编写了以下代码。

流速:

1)询问用户获胜分数

2)生成3个孩子

3)每个人都会生成随机分数并累积它

4)获得胜利分数的人获胜并终止该计划。

void sigHandler(){}
void player(char *, int *, int *, int);
int main(int argc, char *argv[])
{
    int fd1[2], fd2[2], fd3[2], fd4[2], fd5[2], fd6[2], win;
    char turn='T';
    write(1, "This is a 3 player game with a Referee\n", 38);
    printf("Enter the winning score:\n");
    scanf("%d", &win);
    pipe(fd1);
    pipe(fd2);
    if(!fork())
        player("TOTO", fd1, fd2, win);
    sleep(1);
    close(fd1[0]);
    close(fd2[1]);

    pipe(fd3);
    pipe(fd4);
    if(!fork())
        player("TITI", fd3, fd4, win);
    sleep(1);
    close(fd3[0]);
    close(fd4[1]);

    pipe(fd5);
    pipe(fd6);
    if(!fork())
        player("TUTU", fd5, fd6, win);
    sleep(1);
    close(fd5[0]);
    close(fd6[1]);
    while(1)
    {
        signal(SIGINT, sigHandler);
        signal(SIGSTOP, sigHandler);
        write(1,"\nRefree: TOTO plays\n\n", 21);
        write(fd1[1], &turn, 1);
        read(fd2[0], &turn, 1);

        write(1,"\nRefree: TITI plays\n\n", 21);
        write(fd3[1], &turn, 1);
        read(fd4[0], &turn, 1);

        write(1,"\nRefree: TUTU plays\n\n", 21);
        write(fd5[1], &turn, 1);
        read(fd6[0], &turn, 1);
    }
}
void player(char *s, int *fd1, int *fd2, int win)
{
    int points=0, dice;
    char turn;
    srand(time(NULL));
    while(1)
    {
        signal(SIGINT, sigHandler);
        signal(SIGSTOP, sigHandler);
        read(fd1[0], &turn, 1);
        printf("%s: Playing my dice\n",s);
        dice =rand() % 20 + 1;
        printf("%s: got %d points\n", s, dice);
        points+=dice;
        printf("%s: Total so far %d\n\n", s, points);
        if(points>=win)
        {
            printf("%s: GAME OVER. I WON.\n", s);
            kill(0, SIGTERM);
        }
        sleep(3);
        write(fd2[1], &turn, 1);
    }
}

问题是我试图在程序执行时阻止CTRL + Z和CTRL + C信号但是当我使用下面的代码块时它不起作用:

signal(SIGINT, sigHandler);
signal(SIGSTOP, sigHandler);

请提供一些建议。

2 个答案:

答案 0 :(得分:1)

优于虚拟处理程序使用预定义的SIG_IGN(忽略):

signal(SIGINT, SIG_IGN);   /* ignore Terminal interrupt signal */
signal(SIGTSTP, SIG_IGN);  /* ignore Terminal stop signal */

进一步阅读:

答案 1 :(得分:0)

仅需添加一些内容即可得到@Thomas的答案,我仅向您提供一个我自己认为对处理信号有用的链接。

https://www.usna.edu/Users/cs/aviv/classes/ic221/s16/lec/19/lec.html

P.S:正如Thomas所提到的,使用SIG_IGN代替“虚拟”信号处理程序是一个非常整洁而优雅的想法。