【问题标题】:Bash on Ubuntu on Windows: Signal handler does not workWindows 上的 Ubuntu 上的 Bash:信号处理程序不起作用
【发布时间】:2018-03-15 05:30:33
【问题描述】:

我尝试运行一个简单的程序(代码如下),它应该接收并处理SIGUSR1 信号。它在“真正的”Linux 上运行良好,但如果我在发送 SIGUSR1 后在 WSL 上运行它,它会打印出来

用户定义信号1

然后终止。

AFAIK 这意味着程序没有处理 SIGUSR1 并且调用了默认处理程序。如何使 WSL 上的信号处理正常工作?

提前致谢!

源代码:

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

void handle_signal(int signo)
{
    write(1, "Recieved user signal\n", 22);
}

int main()
{
    struct sigaction act;

    act.sa_handler = handle_signal;
    sigfillset(&(act.sa_mask));

    sigaction(SIGUSR1, &act, NULL);

    printf("PID: %d\n", getpid());

    while (1)
        pause();

    return 0;
}

【问题讨论】:

标签: c linux windows signals windows-subsystem-for-linux


【解决方案1】:

以下建议代码:

  1. 正确检查错误
  2. 正确设置 struct sigaction
  3. 干净编译

现在,建议的代码:

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>


void handle_signal(int signo);


void handle_signal(int signo)
{
    if( signo == SIGUSR1 )
    {
        write( 1, "Received user signal\n", 21);
    }
    else
    {
        write( 1, "unexpected signal received\n", 27 );
    }
}


int main( void )
{
    struct sigaction act;

    memset( &act, '\0', sizeof( act ) );
    act.sa_handler = handle_signal;
    //sigfillset(&(act.sa_mask));  // enable catching all signals

    if( sigaction(SIGUSR1, &act, NULL) != 0)
    {
        perror( "sigaction failed" );
        exit( EXIT_FAILURE );
    }

    printf("PID: %d\n", getpid());

    while (1)
        pause();

    return 0;
}

【讨论】:

  • 谢谢,效果很好。为什么原始代码在 linux 上运行良好,但在 WSL 上失败,仍然很奇怪
  • @Wezzer,WSL 从头开始​​实现 Linux 系统调用。显然,在这种情况下,对无效参数的容忍度较低,即未能将 sigaction 记录初始化为零。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-04
  • 1970-01-01
  • 2023-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多