在共享库构造函数中创建线程

标签 c linux pthreads

我想在我的一个 LD_PRELOADed 共享库构造函数中创建一个线程。我目前有以下内容。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void* worker(void* t) {
  sleep(1);
  printf("Running worker..\n");
  return NULL;
}

__attribute__((constructor))
void spawn() {
  pthread_t t;
  printf("[INFO] In the constructor..\n");

  int rc = pthread_create(&t, NULL, worker, (void *)NULL);
  if (rc){
    printf("[FATAL] Failed spawn the thread..\n");
    exit(-1);
  }
}

但是即使调用了构造函数,线程似乎也没有运行。不推荐在 main 之前生成线程吗?我尝试了 gcc 和 g++。

最佳答案

您的主线程没有等待线程完成工作。在 pthread_create 之后添加 pthread_join。

因为我过去一直没有使用过attribute((constructor)),所以我不能对它做太多评论,但是你可以在attribute( (析构函数))。

关于在共享库构造函数中创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49664341/

相关文章:

c - 为什么 C11 不支持 lambda 函数

c++ - 是否可以将 char[][] 传递给请求 char** 的函数?

linux - Linux中进程的网络使用情况

c++ - g++ 默认启用 sse2 吗?

regex - 在 sed 模式中指定 "-"

synchronization - 如何同步两个进程?

c - Free()之前返回0;

c - `getpid()` 是否在进程的每个线程中返回不同的值?

c++ - MIPS 上 pthreads 中的段错误

c++ - 在 Emacs 中为每个目录设置 c-basic-offset