c++ - 调用 pthread_create() 时出现段错误 C++ Linux

标签 c++ linux segmentation-fault pthreads posix

有一段时间没来这里了,但我被困住了…… 我似乎无法弄清楚这段代码的问题出在哪里

记录器.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);
    }
}

记录器.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

主要.cpp

#include "logger.h"

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

代码编译得很好,但是当我运行它时,我在 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;

thread 参数应该指向有效的东西——在您的情况下,您传递的是一个未初始化的指针。也许这与它有关。要确认,请在调试器(例如 gdb)中运行它并查看。

此外,正如您指出这是 C++,您应该真正使用 std::thread()

关于c++ - 调用 pthread_create() 时出现段错误 C++ Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44243486/

相关文章:

c++ - 我可以获得编译器应用的优化日志吗?

c++ - 为什么用静态库编译后可执行文件增长这么多?

linux - 带有否定条件的 if 语句

java - PyLucene : lucene. initVM() 在 linux RHEL7 上导致段错误

c++ - 什么是段错误?

c++ - (C++/winsock) 封装替代结构

c++ - 何时在构造函数中使用 {} ()

linux - 如何使用 cron 守护进程调用脚本

linux - 如何从 nwjs 为 linux 制作应用程序输出?

tensorflow - 为什么 DeepLabV3+ 生成的所有图像都变成黑色?