How to prevent the application launched in Terminal from undesirably exiting?
I launch applications from the Terminal with commands like this one :
/Applications/Mail.app/Contents/MacOS/Mail &
The important part is the &
.
-
For Unix / Linux / Solaris :
- I have learned at school that adding the
&
makes the program live on his own. - I strongly remember launching a command like
xeyes &
and having the program running safe even after I close the shell.
- I have learned at school that adding the
-
On Mac OS X (Unix inside) :
- I launch an app with
&
and I close the Terminal window : the application exits ! - Why does this undesirable behaviour happen on Mac OS X ?
- How can this be fixed ?
- I launch an app with
The "standard" way of accomplishing what you want to accomplish (on OS X as well as on Linux, FreeBSD or other systems) is to use the command nohup
:
nohup program &
This will start program
, which will run in the background relative to the shell because of the &
- and will ignore hangup signals due to the nohup command.
This way the program will continue running even though you close the shell. It doesn't matter if you're closing the shell because you're closing Terminal.app, or you're closing the shell because you are disconnecting from a ssh connection to the computer, or similar.
When you close a terminal window, it sends a SIGHUP (hangup signal) to the shell, which then sends SIGHUP to all the processes it started. This is traditional behavior for bash and many other shells, and the traditional solution to this is to use nohup.
There are ways that different Unix machines can differ, so it's possible that the specific terminal emulators you used or the specific shells you used behaved different. But it's not specific to OS X. For example, there is a question on this same issue on Ubuntu.
Using the ampersand "&
", you are telling Terminal to run the process in the background of the shell itself. Thus, when you close the shell (and kill the process), the GUI (Mail.app itself) will also close.
The correct command to launch Mail from the terminal is simply:
open -a Mail; exit
Edit: I just found this over at U&L Stack Exchange: What does ampersand mean at the end of a shell script line? The answers provided are excellent and explain exactly what's going on in more detail and better than I ever could! I highly recommend reading through it.