In the recent days of writing Linux C service programs, daemon and thread creation have failed.
After the discovery program is daemon, the thread is all hung up.
After checking some documents, I finally got to know why.
The operation of the daemon function is actually very easy,
1.fork a process, 2. Processing 3 standard input and output streams
When you're done, the main process exits and the child process is actually executed.
The child process is hung on the init process, which is the PID 1 process.
The problem occurs at this daemon point in time.
Assuming that after pthread initializes the thread and then daemon, the child process does not have the previous thread, and the previous thread ends up with the main process.
So the correct order is:
Daemon-----> Pthread Create
The same problem also occurs on the fork, the correct order is
Fork-------> Child process pthread Create. Parent process exits
The order problem of Daemon, fork and Creation pthread of C program under Linux