1

Some program has --daemonize option to run itself in background, e.g. php-fpm. I was wondering is there any difference between using --daemonize or just use the old & way to run the process in background?

I would assume there is otherwise why bother to provide --daemonize, why not just run it with &

But I can't find information about that. For example I test php-fpm --daemonize vs php-fpm & and do some limited test. I don't see the difference.

------ update ------

I hit this problem again when trying Dockerfile CMD shell vs exec form.

So maybe it is worth to add a SO discussion here https://stackoverflow.com/questions/42805750/dockerfile-cmd-shell-versus-exec-form

3

& is shell syntax: the shell starts the program in the background, and then keeps tabs on it (e.g., you can use wait to then wait for the background process to finish). Therefore, you need to use a shell for this to work, which may not be desirable or possible in all cases.

--daemonize and similar options are handled by the program itself (it will probably do a double-fork and setsid to dissociate itself from whatever started it), and so they work with other means of starting programs (a fork-and-exec in C, for example).

Which you want to use may depend on how you intend to start the program, and what state you want the program to be in later.

For an unusual example, take sudo. If you want to run a sudo command in the background, but need to authenticate, you can't provide the password if you run sudo foo bar &. One way of course is to authenticate first with a do-nothing command or -v, and then rely on the sudo timeout to run the actual command with & without requiring password input the second time. Another is to run it in the foreground and then send it to the background with CtrlZ and bg. However, sudo has a --background option, where it will run in the foreground, ask for the password, and then daemonize (but then you can't use the shell's job control on it).

There are also other side effects. For example, when running a program in the background with & in bash, if job control isn't active (as is the default in scripts), standard input is set to /dev/null for the new process. With options like --daemonize, it's up to the program to decide what to do with whatever stdin it inherited.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.