我想在我的一个 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/