-1

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

Luk Aron
  • 1,235
  • 11
  • 34
  • 2
    Sounds like your `my_first_process` treats `-D` as an instruction to self-demonize. That's behavior specific to that individual program, not something generally true. – Charles Duffy Mar 23 '20 at 14:13
  • 1
    ...that said, self-daemonization is not a particularly good habit to be in; it's harder for a process supervision system to monitor a server that behaves that way. Certainly do keep it as an option rather than a default, if the program is one you control. – Charles Duffy Mar 23 '20 at 14:16
  • 1
    BTW, that tutorial is showcasing several bad practices. See f/e [Why is testing "$?" to see if a command succeeded or not, an anti-pattern?](https://stackoverflow.com/q/36313216/14122) – Charles Duffy Mar 23 '20 at 14:18

2 Answers2

3

& 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."

Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
1

Some programs, by convention, take -D as an instruction to self-daemonize. Doing this looks something like the following:

  • Call fork(), and exit if it returns 0 (so only the child survives).
  • Close stdin, stdout and stderr if they are attached to the console (ideally, replacing their file descriptors with handles on /dev/null, so writes don't trigger an error).
  • Call setsid() to create a new session.
  • Call 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 &
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441