zap foster
zap foster

Reputation: 231

want thread to not die when parent exits - linux

I do not want to use fork() because that adds a layer of IPC management I wish to avoid. I would like to use a pthread. I have seen an strace for clone, and I don't want to start managing the thread at the clone() level of detail.

To give them names: A=main thread, B=worker thread.

I want B to be able to get a signal from A when A is going away. A can register an atexit() for that.

A may go away either from an abort() or maybe even a SIGSEGV or other terminal signal. B's job is all about logging: A and B share a container with log msgs being created by A. If A dies, I want B to finish logging and THEN exit.

Right now if A exits, B exits, and I lose anything left in the log queue.

So my question is this: is there a way to make B a bit more resilient so it sticks around and doesn't die with A?

Upvotes: 2

Views: 740

Answers (3)

John Humphreys
John Humphreys

Reputation: 39304

I think you wish to create the thread as detached using a pthread_attribute.

https://computing.llnl.gov/tutorials/pthreads/

shows you how - just search down for "detached" :) It will survive after the parent and you can do what you want with it afterward.

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363737

You can install a handler for both atexit and the signals you expect (in A), that pushes a final "I'm done here" message into the logging queue, then joins with (waits for) B before exiting the entire process.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81714

You seem to be confusing threads and processes; the way you describe it, A is a process, not a thread. When abort() is called, or a SIGSEGV is encountered, and A exits, B -- which is a thread contained inside the process A -- disappears as well. There's no way around that, as B is inextricably linked to A. If you want a process to outlive A, then you must use fork and create a new process.

Now, you can absolutely have multiple threads in a process, and thread B could outlive thread A-prime which created it -- but both are subordinate to the process that contains them, and cannot outlive it.

Upvotes: 4

Related Questions