2

I want to run a C function in background but I want it to keep it running when the main function exits.

I tried following:

  1. pthread_detach, a detached thread exits if the main function calls exit() instead of pthread_exit.
  2. deamon(): It runs the code in background but not in parallel.

So, what is the simplest way to run a C function in parallel/background even after my main function exits?

alk
  • 69,737
  • 10
  • 105
  • 255
Kumar Sourav
  • 21
  • 1
  • 2

2 Answers2

1

So, what is the simplest way to run a C function in parallel/background even after my main function exits?

Exit main() by calling pthread_exit().

alk
  • 69,737
  • 10
  • 105
  • 255
  • So by calling this main will instantly exit? Or will it wait till [other] thread terminates and then exit? – aisbaa Aug 06 '15 at 08:41
  • @aisbaa: In a multithreaded enviroment `main()` is just another thread and will be handled as such. So calling `pthread_exit()` from it will end this thread, yes. – alk Aug 06 '15 at 08:46
  • Is this behaviour specified in POSIX or is it Linux-specific? – gavv Aug 06 '15 at 09:06
  • @g-v: I see no reason, why this might be specific to Linux. – alk Aug 06 '15 at 09:20
  • This feature is mentioned in linux man page: "To allow other threads to continue execution, the main thread should terminate by calling pthread_exit() rather than exit(3)." (http://man7.org/linux/man-pages/man3/pthread_exit.3.html). But I didn't find it here: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_exit.html – gavv Aug 06 '15 at 09:24
  • @g-v: Correct, but explicitly being mentioned on the Linux man-page, does not implicitly mean this behaviour is not available on other systems. This kind of logic you seem to apply to conlude something would be fatal. For example even if you did not know me I might very well exist ... :-) – alk Aug 06 '15 at 09:28
  • @g-v: Some answers and comments on your specific question are here: http://stackoverflow.com/q/3559463/694576 and another discussion on this is here: https://groups.google.com/forum/#!topic/comp.programming.threads/b1r0oUwG4rM – alk Aug 06 '15 at 09:35
  • 1
    Thanks. I'm not arguing anything, I'm just wondering if this feature is guaranteed by POSIX specification (explicitly or implicitly). It seems that it *is*, since POSIX explicitly states that ```pthread_exit()``` never releases process-wide resources, so it can't call ```_exit()``` and that process is terminated only if ```_exit()``` is called, signal received, or all running threads exited. – gavv Aug 06 '15 at 10:41
1

Once main returns OS will delete all threads within process. To continue thread use fork to create child process.

Ivan Ivanov
  • 2,076
  • 16
  • 33