Issue
On GNU+Linux, if I run a C program with ./program
, and at some point it calls exit(1)
, does the exit()
call close the terminal window which spawned the program? Because I had some error catching with exit()
and when I came back, the terminal window was gone. My guess is my program hit one of the errors I was responding to with exit()
and that closed the terminal window too? I do know that exit()
destroys the process which calls it as well as all of its child processes and closes all file descriptors currently open by the processes.
One explanation I may (which I'm not sure is correct) have, as to why when I checked on my program the terminal was gone, is that the terminal window from which we typed ./program
to run it with, becomes this process' STDOUT
, which is by default assigned file descriptor 1
. And since exit()
closes all file descriptors, it also closed the terminal window from which I ran the program with?
Solution
There is no "correct" behaviour, and how other processes (e.g. your process' parent) react depends on the environment (and can not be specified by the C standard).
In general; when using "command line" there's 3 different parts: a terminal (or terminal emulator); a shell running inside the terminal (e.g. maybe bash
); and none, one or more process/es running under the shell. For "POSIX-like" environments, when your process terminates its parent process is sent a SIGCHLD signal, and if the parent is a some kind of shell it will handle the SIGCHLD signal by restoring some kind of prompt and waiting for another command to be entered.
However; often there's no shell and its just a bare (virtual) terminal. This is most common when a GUI is starting a console application because GUI environments don't have/use stdin or stdout. To fix that, the GUI will start a terminal emulator to create the stdin/stdout that the console application expects, and then when the console application terminates the terminal emulator has nothing to do (it has no shell or anything) so it also terminates. Of course this can be either convenient or inconvenient, and often terminal emulators for GUIs have command line switches for a "don't close the window when the child terminates" feature.
A ("randomly" selected) example of this is Konsole (the terminal emulator that is part of KDE); where the command line options --hold
or --noclose
will tell the terminal emulator not to close automatically.
Answered By - Brendan Answer Checked By - David Goodson (WPSolving Volunteer)