Alejandro Galera
Alejandro Galera

Reputation: 3691

How to use C popen in a pthread

First, I've been reading some comments in forums about it's recommended to avoid using fork in threads, and popen does fork.

Anyway, I'm doing a program with some threads and it'll be very useful for me to using other library functions which execute popen.

When I do that, program exits.

Let me put a simple example because the code is large:

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) {
...
}

As I told before, "this is NEVER printed" is never printed, and furthermore, main exits, including the other thread called anotherthread

Any piece of help is welcome.

Upvotes: 1

Views: 1017

Answers (1)

alk
alk

Reputation: 70931

main exits, including the other thread

To avoid the behaviour that leaving main() tears down all other threads of the same process. leave it via a call to pthread_exit() instead of doing exit() or just return.

Upvotes: 1

Related Questions