gpt4 book ai didi

在 SharedLibrary 中创建线程会引发段错误

转载 作者:太空宇宙 更新时间:2023-11-04 09:50:48 25 4
gpt4 key购买 nike

我是 linux 操作系统的新手,所以我正在尝试设计一个共享库女巫将启动一个线程,我有以下代码:

  1. 函数 init_log 不会引发段错误,它不会在日志中显示注释,但有人可以告诉我为什么吗?

  2. 函数 pthread_create 引发了一个段错误,我使用 derror() 将其打印在日志中!


void __attribute__ ((constructor)) setup();

void init_log()
{
setlogmask(LOG_UPTO(LOG_NOTICE));
openlog("TRACKER",LOG_CONS | LOG_PID | LOG_NDELAY, LOG_LOCAL1);
}

void loop()
{
while (0 == 0)
{
syslog(LOG_NOTICE,"OK BOSS");
sleep(1000);
}
}

void setup()
{
pthread_t thread_id;
init_log();
syslog(LOG_NOTICE,"LIB LOADED"); // this doesn't display
pthread_create(&thread_id,0,&loop,(void*)(NULL));
}

编译器链接参数

**** Build of configuration Debug for project gt_trackers ****

make all
Building target: libgt_trackers.so
Invoking: GCC C Linker
gcc -shared -o "libgt_trackers.so" ./main.o
Finished building target: libgt_trackers.so

**** Build Finished ****

最佳答案

函数 void loop() 应该是 void *loop (void *)

pthread_create 的调用应该是

pthread_create(&thread_id,0,loop,NULL); 

pthread_create 的原型(prototype)如下。您应该将循环函数的原型(prototype)与下面提到的“start_routine”相匹配。

int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);

另一点是,只要提供一个函数的名称就足以传递它的地址。无需在其前添加 &

Pthread 教程链接:https://computing.llnl.gov/tutorials/pthreads/

正如 alk 所指出的,也不需要对“NULL”进行类型转换。谢谢你。 :)

关于在 SharedLibrary 中创建线程会引发段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11326018/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com