5

I had a FreeBSD machine and it had a /usr/sbin/daemon command which could run my program in the background.

The question is how to do something similar in Ubuntu? I would like something I can put in a startup script.
What I mean is my program can't put itself in a background when starts.

I tried:

start-stop-daemon --start --quiet --pidfile $PIDSPATH/$PIDFILE --exec $DAEMON

But it just starts the program and I must wait for it to finish.

Sergey
  • 616

2 Answers2

7

Use the --background option of start-stop-daemon. From the manual page of start-stop-daemon(8):

-b, --background
Typically used with programs that don't detach on their own. This option will force start-stop-daemon to fork before starting the process, and force it into the background. WARNING: start-stop-daemon cannot check the exit status if the process fails to execute for any reason. This is a last resort, and is only meant for programs that either make no sense forking on their own, or where it's not feasible to add the code for them to do this themselves.

In a shell, programs can be backgrounded with & as in:

$ myprogram &
[1] 5042
Lekensteyn
  • 174,277
  • how do I run a command with the arguments with & ? I tried "my_command args" & but it didn't work, although my_command args by itself worked well. – Incerteza Mar 15 '14 at 16:52
  • @Alex my_command args & works too. The jobs builtin will show you the program with the Running label. What makes you think that it doesn't work? – Lekensteyn Mar 15 '14 at 19:53
  • @Lekensteyn, yes, you're right. – Incerteza Mar 16 '14 at 00:19
  • the 'nohup' program was designed for exactly this and has been around since the inception of unix. has no one heard of it lol? – Ronald Johnson May 08 '23 at 22:20
3

If you're just looking to run something and detach it (so it runs in the background) there are half a dozen methods that I evaluated yesterday. The easiest is just to wrap the command in parenthesis:

(command)

You can close the terminal and move on with life and the application will keep running. There's obviously no control over the process now short of looking it up and nuking it (kill, killall, etc), or it quitting itself.

If you need something a bit more elegant, I'd look at upstart scripts. Upstart is the replacement for the System V init system (ie the files in /etc/init.d/). To give you an idea of how an Upstart script looks, you can see the existing Upstart jobs in /etc/init/.

There's a lovely cookbook of examples on the Upstart website:

Oli
  • 293,335