首先,我一直在论坛上阅读一些关于它的评论,建议避免在线程中使用fork
,而popen
会做分叉。
无论如何,我正在用一些线程做一个程序,对我来说使用执行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) {
...
}
正如我之前所说的那样,“永远不会打印”从未打印过,而且还有主要出口,包括另一个名为anothesteread的线程
欢迎任何帮助。
主要退出,包括其他主题
为了避免让main()
撕下同一进程的所有其他线程的行为。通过调用pthread_exit()
而不是做exit()
或只是return
离开它。