According to this docker tutorial
What's the difference between
./my_first_process -D
./my_main_process &
They both seem unblocking to bash script and run in background
According to this docker tutorial
What's the difference between
./my_first_process -D
./my_main_process &
They both seem unblocking to bash script and run in background
&
tells the shell to put the command that precedes it into the background. -D
is simply a flag that is passed to my_first_process
and is interpreted by it; it has absolutely nothing whatsoever to do with the shell.
You will have to look into the documentation of my_first_process
to see what -D
does … it could mean anything. E.g. in npm
, -D
means "development", whereas in some other tools, it may mean "directory". In diff
, it means "Output merged file to show `#ifdef NAME' diffs."
Some programs, by convention, take -D
as an instruction to self-daemonize. Doing this looks something like the following:
fork()
, and exit if it returns 0 (so only the child survives)./dev/null
, so writes don't trigger an error).setsid()
to create a new session.fork()
again, and exit if it returns 0 again.That's a lot more work than what just someprogram &
does! A program that has self-daemonized can no longer log to the terminal, and will no longer be impacted if the terminal itself closes. That's not true of a program that's just started in the background.
To get something similar to the same behavior from bash, correct code would be something like:
someprogram </dev/null >/dev/null 2>&1 & disown -h
...wherein disown -h
tells the shell not to pass along a SIGHUP to that process. It's also not uncommon to see the external tool nohup
used for this purpose (though by default, it redirects stdout and stderr to a file called nohup.out
if they're pointed at the TTY, the end purpose -- of making sure they're not pointed at the terminal, and thus that writes to them don't start failing if the terminal goes away -- is achieved):
nohup someprogram >/dev/null &