Detaching thread in C++11 - multithreading

I want to start a thread from a process and detach it and terminate the process. But the thread will be running continuously in the background. Can I achieve this with c++11 ?
I have detached my thread like this
std::thread(&thread_func, param1, param2).detach();
But it gets terminated once the process is terminated.

Detaching is not the same as running in the background. If you detach a thread then you simply tell the OS "I don't want to join the thread manually after it exits, please take care of that for me". But the OS will usually kill all child threads/processes when the main process exits.
So what you want is to run a deamon. However turning a process into a deamon (note that you can't daemonize a thread) is OS dependent. On linux you would call daemon function:
http://man7.org/linux/man-pages/man3/daemon.3.html
I don't know how to do that on Windows or other OS. Also you may want to read this:
Creating a daemon in Linux

Related

Linux fork, execve - no wait zombies

In Linux & C, will not waiting (waitpid) for a fork-execve launched process create zombies?
What is the correct way to launch a new program (many times) without waiting and without resource leaks?
It would also be launched from a 2nd worker thread.
Can the first program terminate first cleanly if launched programs have not completed?
Additional: In my case I have several threads that can fork-execve processes at ANY TIME and THE SAME TIME -
1) Some I need to wait for completion and want to report any errors codes with waitpid
2) Some I do not want to block the thread and but would like to report errors
3) Some I don't want to wait and don't care about the outcome and could run after the program terminates
For #2, should I have to create an additional thread to do waitpid ?
For #3, should I do a fork-fork-execve and would ending the 1st fork cause the 2nd process to get cleaned up (no zombie) separately via init ?
Additional: I've read briefly (not sure I understand all) about using nohup, double fork, setgpid(0,0), signal(SIGCHLD, SIG_IGN).
Doesn't global signal(SIGCHLD, SIG_IGN) have too many side effects like getting inherited (or maybe not) and preventing monitoring other processes you do want to wait for ?
Wouldn't relying on init to cleanup resources leak while the program continues to run (weeks in my case)?
In Linux & C, will not waiting (waitpid) for a fork-execve launched process create zombies?
Yes, they become zombies after death.
What is the correct way to launch a new program (many times) without waiting and without resource leaks? It would also be launched from a 2nd worker thread.
Set SIGCHLd to SIG_IGN.
Can the first program terminate first cleanly if launched programs have not completed?
Yes, orphaned processes will be adopted by init.
I ended up keeping an array of just the fork-exec'd pids I did not wait for (other fork-exec'd pids do get waited on) and periodically scanned the list using
waitpid( pids[xx], &status, WNOHANG ) != 0
which gives me a chance report outcome and avoid zombies.
I avoided using global things like signal handlers that might affect other code elsewhere.
It seemed a bit messy.
I suppose that fork-fork-exec would be an alternative to asynchronously monitor the other program's completion by the first fork, but then the first fork needs cleanup.
In Windows, you just keep a handle to the process open if you want to check status without worry of pid reuse, or close the handle if you don't care what the other process does.
(In Linux, there seems no way for multiple threads or processes to monitor the status of the same process safely, only the parent process-thread can, but not my issue here.)

Do I need to check for my threads exiting?

I have an embedded application, running as a single process on Linux.
I use sigaction() to catch problems, such as segmentation fault, etc.
The process has a few threads, all of which, like the app, should run forever.
My question is whether (and how) I should detect if one of the threads dies.
Would a seg fault in a thread be caught by the application’s sigaction() handler?
I was thinking of using pthread_cleanup_push/pop, but this page says “If any thread within a process calls exit, _Exit, or _exit, then the entire process terminates”, so I wonder if a thread dying would be caught at the process level …
It is not a must that you need to check whether the child thread is completed.
If you have a need of doing something after the child thread completes its processing you can call thread_join() from the main thread, so that it will wait till the child threads completes execution and you can do the rest after this. If you are using thread_exit in the main thread it will get terminated once it is done, leaving the spawned threads to continue execution. The process will get killed only after all the threads completes execution.
If you want to check the status of the spawned threads you can use a flag to detect whether it is running or not. Check this link for more details
How do you query a pthread to see if it is still running?

Kernel mode in multithreaded program

If a thread in a process makes system call then in uni-threaded process, process will switch o kernel mode. But what will in case of multi-threaded process?
In other words, if a thread in a process makes system call then what is mode of the process which contains that thread -- kernelmode/user mode?
In Linux a thread is simply a process that happens to share memory with several other processes (other threads within the same process).
So, the CPU will be system mode during the syscall, but the execution will still switch to some other thread or process when its time slice expires, just like it normally switches from process to process even if the currently running process is executing a syscall.

How to kill thread spawned using CLONE_THREAD and blocked on a shared resource in kernel space?

I have a test case where there are threads spawned using CLONE_THREAD option in clone() .Here if i want to kill a particular thread I suppose we should be using SYS_tgkill in systemcall(). But will the kill actually affect a thread if it is waiting in kernel space(say a futex_wait)?
I tried killing a thread created in the above manner.But when SIGKILL is sent to the same the whole process is getting killed.Am i missing something in using syscall(SYS_tgkill,pid,tid,9) ?
SIGKILL always kills the target process. There is no way around this; it's unblockable, unignorable, and uncatchable.
You could try sending another signal (like SIGUSR1 or SIGHUP or SIGRTMIN) and having a signal handler installed that calls pthread_exit (but note that this function is not async-signal-safe, so you must ensure that the signal handler did not interrupt another async-signal-unsafe function) or use cancellation (pthread_cancel) to stop the blocked thread.
This should work for normal blocking operations (like waiting for data from a pipe or socket), but it will not help you if the thread is in an uninterruptable sleep state (like trying to read from a badly scratched CD or failing hard disk).

Use of SIGCONT with CLONE() and CLONE_STOPPED flag set for Linux

I am trying to implement a thread create/run function using clone().I am planning to use CLONE_STOPPED flag to create a child thread but let it wait for starting execution until i send SIGCONT to the child thread created.The doubt i am having is what will be the state of parent thread when it sends SIGCONT to the child and the child resumes execution.Will the parent thread be suspended ? or continue running ?.How can we configure this.?
THanks in advance!
The parent will continue to be runnable. Whether it actually runs simultaneously with the child or interleaved depends on how many processor cores you have and how the scheduler decides to run them; you should assume it runs simultaneously.
The CLONE_STOPPED flag has been deprecated for years, and was actually removed during the latest kernel merge window. You should not be using it - use thread synchronisation primitives (perhaps built on futex()) instead.

Resources