Skip to content
Advertisement

How many ways will a process be terminated in Linux?

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:

  1. Return from main
  2. Calling exit
  3. Calling _exit or _Exit
  4. Return of the last thread from its start routine (Section 11.5)
  5. Calling pthread_exit (Section 11.5) from the last thread

for

  1. Return of the last thread from its start routine (Section 11.5)
  2. 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

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,

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement