[英]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 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 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 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? 代码可以很好地编译,但是当我运行它时,在pthread_create()调用期间出现了段错误...有什么想法吗? I have stripped away everything in the program and I still get the same crash...
我已经剥离了程序中的所有内容,但仍然遇到相同的崩溃...
From the man page of pthread_create()
: 在
pthread_create()
的手册页中:
Before returning, a successful call to pthread_create() stores the ID of the new thread in the buffer pointed to by thread;
返回之前,对pthread_create()的成功调用将新线程的ID存储在线程指向的缓冲区中。
The thread
argument should point to something valid - in your case you are passing in an un-initialized pointer. thread
参数应该指向有效的东西-在您的情况下,您传入的是未初始化的指针。 Perhaps this has something to do with it. 也许这与它有关。 To confirm, run it in a debugger (such as gdb) and take a look.
要确认,请在调试器(例如gdb)中运行它,然后看一下。
Also, as you indicate this is c++, you should really use std::thread()
. 另外,正如您指出的是c ++一样,您应该真正使用
std::thread()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.