Bash on Ubuntu on Windows:信号处理程序不工作
Bash on Ubuntu on Windows: Signal handler does not work
我尝试 运行 一个简单的程序(下面的代码),它应该接收和处理 SIGUSR1
信号。它在 "real" Linux 上运行良好,但如果我在发送 SIGUSR1
后在 WSL 上 运行 它会打印
User defined signal 1
并终止。
据我所知,这意味着 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;
}
建议代码如下:
- 正确检查错误
- 正确设置 struct sigaction
- 干净地编译
现在,建议的代码:
#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, '[=10=]', 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;
}
我尝试 运行 一个简单的程序(下面的代码),它应该接收和处理 SIGUSR1
信号。它在 "real" Linux 上运行良好,但如果我在发送 SIGUSR1
后在 WSL 上 运行 它会打印
User defined signal 1
并终止。
据我所知,这意味着 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;
}
建议代码如下:
- 正确检查错误
- 正确设置 struct sigaction
- 干净地编译
现在,建议的代码:
#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, '[=10=]', 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;
}