Pthread_exit in a signal handler causes a segmentation error

The program below sets the SIG_ALRM handler for the entire process, creates a thread, sends the SIG_ALRM signal to the newly created thread. In the SIG_ALRM handler, pthread_exit is called. The result is a segmentation error. If you sleep before sending a signal - OK.

It appears that the new thread was not running at the time of pthread_exit. I tried to find a segmentation error using gdb but could not reproduce the failure using gdb.

What causes a segmentation error?

Thank!

#include <signal.h>
#include <pthread.h>
#include <iostream>
#include <cassert>
using namespace std;

void* threadFunc(void* arg) {
    cout << "thread: started. sleeping..: " << pthread_self() << endl;
    sleep(10);
    cout << "thread: exit" << endl;
    return NULL;
}

void alrm_handler(int signo) {
    cout << "alrm_handler: " << pthread_self() << endl;

    pthread_exit(NULL); //if comment - no segmentation fault
}

int main() {
    cout << "main: " << pthread_self() << endl;

    struct sigaction act;
    act.sa_handler = alrm_handler;
    act.sa_flags = 0;
    sigemptyset(&act.sa_mask);
    sigaction(SIGALRM, &act, NULL);

    pthread_t t;
    int rc = pthread_create(&t, NULL, threadFunc, NULL);
    assert(rc == 0);

//  usleep(1000); //if Uncomment - no segmentation fault
    rc = pthread_kill(t, SIGALRM);
    assert(rc == 0);

    pthread_join(t, NULL);

    cout << "main: exit" << endl;
    return 0;
}

Output:

main: 140130531731232
alrm_handler: 140130504095488
segmentation error

+1
source share
2 answers

. - .

  usleep(1000); 
+1

pthread_exit . , , - . , pthread_create async-signal-unsafe - , , - " pthread_create" ( -), .

+4

Source: https://habr.com/ru/post/1659481/


All Articles