【问题标题】:Creating a thread in a shared library constructor在共享库构造函数中创建线程
【发布时间】:2018-04-05 04:47:20
【问题描述】:

我想在我的 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++。

【问题讨论】:

  • 发布minimal reproducible example。为什么要标记 c++?
  • 它对我有用。假设您发布的内容是在 bar.c 中,并且在 foo.c 中只是睡了一会儿,cc -o foo foo.c &amp;&amp; cc -pthread -fPIC -shared -o bar.so bar.c &amp;&amp; LD_PRELOAD=./bar.so ./foo
  • 我不确定它是否应该工作,但库在不被询问的情况下创建线程通常不是一个好主意。
  • 哇。我完全误解了这个问题。还好我没有写任何让我看起来像个白痴的东西。有什么方法可以保留rc 以监控其状态?
  • 好的。它现在似乎正在工作。我现在确实觉得自己像个白痴。看起来一些缓存的目标文件是问题的原因。但总的来说,我想知道这是否被推荐。似乎没有?我猜这不是标准化的行为。@Stargateur 我现在已经删除了 c++ 标签。我也包括在内,因为我也尝试过 g++。

标签: c linux pthreads


【解决方案1】:

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

由于我没有使用attribute((constructor))任何时候都过去了,我不能对此发表太多评论,但是您可以在attribute中添加pthread_join( (析构函数))。

【讨论】:

  • 这个答案的问题:正在创建的工作线程在库加载函数中。实际的main 函数稍后出现。对于一个重要的示例线程,此答案将阻止进入main 并启动库用户的代码。很容易造成死锁。
猜你喜欢
  • 1970-01-01
  • 2015-09-05
  • 2011-08-04
  • 1970-01-01
  • 2016-06-23
  • 1970-01-01
  • 1970-01-01
  • 2020-04-26
  • 1970-01-01
相关资源
最近更新 更多