1

Why doesn't the program end? The child hangs after printing what it has to print. If the parent process slept instead of the child, It would have worked, but why is that? I have also tried calling exit at the end of each process, but with the same result. Do I always have to wait for the child to finish?

int main(){

    int pid = fork();

    char s[100] = "Hello";

    if(pid > 0){
        printf("FIRST PRINT IN PARENT: %s\n", s);
        strcat(s, " - PARENT");
        printf("SECOND PRINT IN PARENT: %s\n", s);
    }
    else if(pid == 0){
        printf("IMMEDIATELY IN CHILD: %s\n", s);
        sleep(2);
        printf("AFTER 2 SCONDS IN CHILD: %s\n", s);
    }
    return 0;
}
Toma Radu-Petrescu
  • 2,152
  • 2
  • 23
  • 57
  • 1
    Are you *sure* it "hangs"? It's not that the terminal prints the output of the child, and simply does not display the prompt again? Try pressing the `Enter` key and see what happens. Also, if you look closely in your terminal, you will probably *see* the prompt before the last output of the child. – Some programmer dude Jan 31 '17 at 11:57
  • 1
    Not you, but your _shell_ waits for the _parent_ process to terminate. You would have to double-fork to regain the shell prompt instantly – Ctx Jan 31 '17 at 11:58
  • The code works for me. If you suspect it is "hanging", is it still visible in `ps` output? – cdarke Jan 31 '17 at 12:14

2 Answers2

1

When the parent exits it might send a signal (SIGHUP) to the child. If it does, and if the child doesn't catch that signal, the child dies.

Historically, the default has been for a process to send SIGHUP to it's children when it exits. Nowadays, many Linux distributions don't send SIGHUP by default.

I tried your code on RHEL and the child process wasn't killed. So the parent dies and control returns to the shell. The child continues and prints it's second output 2 seconds later.

If the child does receive a SIGHUP it won't hang. It dies, and the final string is never printed.

In Linux, you can turn on SIGHUP via the prctl system call:

#include <sys/prctl.h>
prctl(PR_SET_PDEATHSIG, SIGHUP);

Related question: how-to-make-child-process-die-after-parent-exits

Community
  • 1
  • 1
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
0

The shell does give you the prompt back once its child process (i.e. the parent process in your code) exits. However, it doesn't know about the child process your code started.

The source of problems you have observed is that your parent process doens't wait for its child. Use wait(2) system call, such as wait(0);, in the parent process.

The general risk of not waiting for child process(es) is that you might end up with zombie processes; conversely, orphan processes (if you parent process exits first).

P.P
  • 117,907
  • 20
  • 175
  • 238