gpt4 book ai didi

c - 如何在 pthread 中使用 C popen

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

首先,我在论坛上阅读了一些关于建议避免在线程中使用 fork 的评论,而 popen 会进行 fork。

无论如何,我正在编写一个带有一些线程的程序,它对我使用其他执行 popen 的库函数非常有用。

当我这样做时,程序退出。

因为代码量大,我举个简单的例子:

int main()
{
pthread_t thread1, thread2;
int var=1;
pthread_create(&thread1, NULL, mythread, &var);
pthread_create(&thread2, NULL, anotherthread, &var);
...
}

void *mythread(void *s)
{
...
pthread_detach(pthread_self());
...
printf("this is printed\n");
char *str = externalFunctWithPopen();
printf("this is NEVER printed\n");
...
}

char *externalFunctWithPopen()
{
...
printf("this is also printed\n");
popf = popen(command, "r");
printf("this is not printed at all\n");
while (fgets(buf, sizeof(buf), popf) != 0) {
...
}

正如我之前所说,"this is NEVER printed" 永远不会被打印,此外,main 退出,包括另一个名为 anotherthread

的线程

欢迎任何帮助。

最佳答案

main exits, including the other thread

避免离开 main() 的行为会破坏同一进程的所有其他线程。通过调用 pthread_exit() 而不是执行 exit() 或只是 return 来离开它。

关于c - 如何在 pthread 中使用 C popen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54764754/

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