Skip to content

pthread_kill signal not caught by signal handler #22274

@hly2019

Description

@hly2019

Please include the following in your bug report:

Version of emscripten/emsdk:
3.1.54

Failing command line in full:
Hi, it seems when I use pthread_kill to send signals (SIGINT, for example) to threads, the signal I sent can't be caught by the signal handler. It looks like directly terminating the thread.

For example, in the following code, the compiled Wasm program just terminated and aborted, but I'd expect the SIGINT signal could be caught by the signal handler.

I found a related issue 14872 discussing the pthread_kill implementation, saying it's terminating threads instead of sending signals. Is this problem still remaining?

I'd appreciate it so much if you could take a look at it. Thank you very much!

Code

#include <thread>
#include <signal.h>
#include <stdio.h>
void setupSignalHandlers() {
    struct sigaction act;
    sigemptyset(&act.sa_mask);
    act.sa_flags = SA_SIGINFO;
    act.sa_sigaction = [](int sig, siginfo_t *, void *) {
        printf("signal: %d\n", sig);
    };
    sigaction(SIGINT, &act, nullptr);
}
int main() {
    bool thread_done = false;
    auto thread = std::thread([&]() {
        setupSignalHandlers();
        thread_done = true; // make sure setupSignalHandlers is called
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    });
    while(!thread_done) { // make sure setupSignalHandlers() is called
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }
    pthread_kill(thread.native_handle(), SIGINT); // seems not caught by the signal handler
    thread.join();
    return 0;
}

Compilation

# with emcc
$ emcc test_thread.cpp -o main.js -pthread -sNO_DISABLE_EXCEPTION_CATCHING -g; node main.js

# with native
$ g++ test_thread.cpp -o main; ./main

Results

# with wasm
Aborted(native code called abort())
/data/main.js:147
      throw ex;
      ^

RuntimeError: Aborted(native code called abort())
    at abort (/data/main.js:741:11)
    at _abort (/data/main.js:2130:7)
    at invoke_v (/data/main.js:2456:29)
    at main.wasm.std::__terminate(void (*)()) (wasm://wasm/main.wasm-008381ea:wasm-function[713]:0xf8ee)
    at main.wasm.std::terminate() (wasm://wasm/main.wasm-008381ea:wasm-function[711]:0xf8cf)
    at main.wasm.std::__2::thread::~thread() (wasm://wasm/main.wasm-008381ea:wasm-function[563]:0xe628)
    at main.wasm.__original_main (wasm://wasm/main.wasm-008381ea:wasm-function[41]:0x15c3)
    at main.wasm.main (wasm://wasm/main.wasm-008381ea:wasm-function[127]:0x3f79)
    at /data/main.js:791:12
    at callMain (/data/main.js:2816:15)

Node.js v20.11.0

# with native, no error
signal: 2

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions