简体   繁体   中英

segfault when calling pthread_create() c++ linux

Haven't been here for a while but I'm stuck... I can't seem to figure out where the problem lies with this code

logger.cpp

#include "logger.h"
#include <unistd.h>
#include <stdlib.h>

void* __logger(void* data)  // dummy function
{
    sleep(10);
    return NULL;
}

logger_t::logger_t()
{
    // create a pipe for communicating with thread
    if (pipe(fd) == -1) // something went wrong
    {
        // error here
        exit(EXIT_FAILURE);
    }
    // now create the thread that will write to the log
    if (pthread_create(log_pid, NULL, &__logger, NULL))  // something went wrong
    {
        exit(EXIT_FAILURE);
    }
}

logger_t::~logger_t()
{
    close(fd[1]);     // close read end of pipe, logging thread will read EOF and exit
    if (pthread_join(*log_pid, NULL))
    {
        exit(EXIT_FAILURE);
    }
}

logger.h

#ifndef LOGGER_H
#define LOGGER_H
#include <pthread.h>

class logger_t
{
    public:
        logger_t();
        ~logger_t();

    private:
        int fd[2];
        pthread_t* log_pid;
};
#endif // LOGGER_H

main.cpp

#include "logger.h"

int main()
{
    logger_t proglog;
    return 0;
}

The code compiles just fine but when I run it I get a segmentation fault during the pthread_create() call... Any ideas? I have stripped away everything in the program and I still get the same crash...

From the man page of pthread_create() :

Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread;

The thread argument should point to something valid - in your case you are passing in an un-initialized pointer. Perhaps this has something to do with it. To confirm, run it in a debugger (such as gdb) and take a look.

Also, as you indicate this is c++, you should really use std::thread() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM