I’m reading Advanced Programming in the Unix Environment 3rd Edn, §7.3, Process Termination, the following statement make me confused:
There are eight ways for a process to terminate. Normal termination occurs in five ways:
- Return from main
- Calling exit
- Calling _exit or _Exit
- Return of the last thread from its start routine (Section 11.5)
- Calling pthread_exit (Section 11.5) from the last thread
for
- Return of the last thread from its start routine (Section 11.5)
- Calling pthread_exit (Section 11.5) from the last thread
I don’t think a process will terminate if it is not returned form main function even though the last thread in this process is terminated, am I right? If not, why 4 and 5 are right?
Advertisement
Answer
The main
thread is one of the threads. For example, in
JavaScript
x
void *start(void *arg) {
sleep(1);
pthread_exit(0);
}
int main() {
pthread_t t;
pthread_create(&t, 0, start, 0);
pthread_exit(0);
}
the main thread exits immediately, but the process continues running until the last thread has exited. This is true the other way around,
JavaScript
void *start(void *arg) {
pthread_exit(0);
}
int main() {
pthread_t t;
pthread_create(&t, 0, start, 0);
sleep(1);
pthread_exit(0);
}
where the main thread is the last one left.