The child thread in this code blocks the shell, even after the main process exits. How do I make it run in the background and not block the shell? I see it is possible with fork(), but I do not want to create a whole new process.
Thank you.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void * myThreadFun (void *vargp)
{
while (1)
{
//Do useful work continuously
sleep (1);
}
}
int
main ()
{
pthread_t tid;
pthread_create (&tid, NULL, myThreadFun, NULL);
pthread_detach (tid);
printf ("After Thread\n");
pthread_exit (0);
}
In a multi-threaded program, there is no way for the main thread to actually exit and leave spawned threads running. If you need this program to continue running when you execute it from a shell but immediately return to a shell prompt, i.e., run in the background, you will have to use fork().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With