views:

95

answers:

4

Hi everyone,

Some programs return immediately when launched from the command line, Firefox for example. Most utilities (and all the programs I've written) are tied to the shell that created them. If you control-c the command line, the program's dead.

What do you have to add to a program or a shell script to get the return-immediately behavior? I guess I'm asking two questions there, one for shell scripts and one for general, if they're different. I would be particularly interested to know if there's a way to get an executable jar to do it.

I'm almost embarrassed to ask that one but I can't find the answer myself.

Thanks!

+3  A: 

You need to basically need to fork a process or create a new thread (or pretend to)

in *nux you can do this with an & after the command like this /long/script & or in windows you can create a BATCH file that executes your processes then exits (it does this naturally).

NOTE: there's no particularly good way to reference this process after you're forked it, basically only ps for the process list. if you want to be able to see what the process is doing, check out using screen (another linux command) that will start a session for you and let you "re-attach" to the screen.

to do this, install screen (sudo apt-get install screen or yum install screen). then type screen to create a new session (note, it will look like you didn't do anything). then, run your /long/command (without the &), then press CTRL + A + D (at the same time) to detach from it (it's still running!). then, when you want to re-attach, type screen -r.

Additionally, look for flags in any help message that allow you do this without using the above options (for instance in synergy you can say synergy --background)

Dan Beam
+2  A: 
start cmd 

on Windows,

cmd &

on *nux

Here substitute

cmd = java -jar JarFile.jar

On *nux the fg and bg commands are your friends as well ...

Hamish Grubijan
Yuvi Masory
As Dennis said, nohup is your friend. Then kill by pid using top etc.
Hamish Grubijan
+1  A: 

For an executable program (as opposed to a shell script), on Linux/Unix use fork() and exec() and then exit the parent process, which will return to the shell. For details see the man pages, or some page like http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html.

garyo
thank you! And Dennis too. It seems like nohup and fork/exec are the answers I was looking for.
Yuvi Masory
see also the daemon() call which will make it a true background process (detach from the tty and create a new session)
nos
+1  A: 

A wrapper script consisting of nothing but:

your_prog_or_script &

Will launch the target and exit immediately. You can add nohup to the beginning of that line so it will continue running if the shell is exited.

Dennis Williamson