Reputation: 13
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...
Upvotes: 0
Views: 237
Reputation: 33645
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()
.
Upvotes: 2