Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make pthread work in background and not block the shell?

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);
}
like image 214
Arjun Bora Avatar asked Nov 21 '25 08:11

Arjun Bora


1 Answers

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().

like image 60
Duane McCully Avatar answered Nov 24 '25 00:11

Duane McCully



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!