【问题标题】:SIGQUIT, Handling the Second signal with quick, successive callsSIGQUIT,通过快速、连续的调用处理第二个信号
【发布时间】:2019-08-09 04:12:55
【问题描述】:

我试图忽略第一个SIGQUIT 到子线程... 具体来说,在每次调用后写入控制台并在第二次调用时退出。

我已经尝试过此代码的变体;即每个类似的堆栈溢出线程分成两个函数。不幸的是,对于孩子的处理程序来说,父循环似乎“太快了”。

SIGQUIT 的处理程序:

int goes = 0;

void install_handler(){ 

    write(1, "SIGQUIT\n", 8);

    if (goes == 1) exit(0); 

        goes += 1;
}

只是司机:

{
    if((child_pid = fork()) < 0) exit(1);

    if (child_pid == 0 ) { 

        signal(SIGQUIT, install_handler);

        while(1){}

    } else { 

        sleep(1);

        for (int i = 0; i < 3; i++) { 

        write(1, "KILLING\n", 8);

        kill(child_pid, SIGQUIT);

      //  sleep(1);


        }
    }
    return 0;
}

我希望输出是 ~

KILLING
SIGQUIT
KILLING
SIGQUIT
KILLING
...

输出(父循环中没有睡眠)是

KILLING
KILLING
KILLING
SIGQUIT
SIGQUIT

这不是我想要达到的顺序。什么是确保在 sigquit 的每个信号上我们可以保证在不修改 main() 方法的情况下将“SIGQUIT”写入控制台的有效方法?

【问题讨论】:

  • 这看起来像是 XY 问题。为什么你需要像这样交错输出?信号是异步的,kill() 调用返回的事实并不意味着信号已被处理 - 它受调度的影响。
  • 100% 需要这样的交错!输出是字符串匹配的!

标签: c linux signals


【解决方案1】:

您的问题有一个有趣的答案。 但首先虽然很烦人,但我不允许发表评论,所以我希望我没有犯任何错误。

int goes = 0;
int child_pid = 0;

void install_handler(){ 
if (child_pid == 0) exit(0); //to exit the program once done
write(1, "SIGQUIT\n", 8);
kill(child_pid, SIGQUIT);
write(1, "KILLING\n", 8);
//you can put it after the if depending on the output
if (goes == 1)  {
kill(0, SIGQUIT);
exit(0);
} //this way the program will end himself at the end
// i guess the fact that goes was indented is a mistake
goes += 1;
}

如您所见,我将 kill 放入处理程序中,这样在收到另一个 kill 之前不会发送 kill。 (注意我在这里是如何调用 pid 的?)

{
    if((child_pid = fork()) < 0) exit(1);

if (child_pid == 0 ) { 



    while(1){
        signal(SIGQUIT, install_handler);
    }

} else { 

    sleep(1);
    kill(child_pid, SIGQUIT);
    write(1, "KILLING\n", 8);
    for (int i = 0; i < 3; i++) { 
    signal(SIGQUIT, install_handler);
    wait(); //you might even not need the wait!


  //  sleep(1);


    }
}
return 0;

}

我强烈建议使用 sigaction 而不是 signal,它更精确。 我必须说我不确定我的答案,因为我在这台计算机上没有 c 但通常我使用 sigaction 并等待(而不是睡眠) 你也不需要调用它 child_pid 因为它是子 pid 也不是子 pid,因为它是两个进程

soooo...我希望我有用!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-14
    • 2014-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多