Shell – IO and other shell commands when a program is not started by a terminal

posixshellstdinstdoutterminal

I have several launchers on my desktop for various programs, and there is a "run in a terminal" setting for those launchers.

When I check that setting, the program runs from a terminal, and logs its output there. I suppose that it could read stdin from the terminal too.

However: what happens to IO when the program is not ran by a terminal? Also, what happens when I execute system (shell) commands from a program like that?

Is there a "background" shell that runs those programs? Or does every program get its shell through which it interfaces with the rest of the system?

Best Answer

When a program is launched (by one of the exec(3) family of system calls), it inherits the environment (i.e., shell variables exported) and the open files from the parent. What is done when launching a program is a fork(2), the child sets up the environment and files, then exec(3)s the new program. When a shell does this, STDIN, STDOUT and STDERR are connected to the terminal. What any graphic launcher does is up to it, but is should connect them to /dev/null (where should keyboard input come from, and where should output go to?).

If a program launched like that in turn calls exec(3), it is as explained above. system(3) is a bit more complex, as it spawns a shell to do command line parsing and so on, and that shell then exec(3)s the command. But the mechanics is the same: Files are inherited, as is the environment.

Related Question