1

Situation1

command

  1. find / -name "*.conf"
  2. Ctrl+Z to pause the process

Situation2

--- hello.sh ---

#!/bin/bash
/bin/sleep 5000

command
./hello.sh &

Situation3

command
nohup ./hello.sh &

finally
command

pstree | less to get the processes info

|-sshd-+-sshd
|      |-sshd---bash
|      `-sshd---bash-+-find
|                    |-2*[hello.sh---sleep]
|                    |-less
|                    `-pstree

then I exit the ssh

I get the pstree info in another ssh

init-|      
     |-2*[hello.sh---sleep]  

question

  1. Why do I run hello.sh and use nohup to suspend hello.sh, the result will be the same?
  2. Why does the find process not appear like the hello.sh process? When parent process was killed , init process will possess the orphan process.
  3. Is it necessary to use nohup if I want background a process?
Arronical
  • 19,653
  • 18
  • 73
  • 128
Sung Qee
  • 113
  • 4
  • In situation 2, if im not mistaken, if process needs to read from stdin , it will be stopped. Once shell closes, its background process will be closed too. Nohup allows exiting shell and keeping program running. – Sergiy Kolodyazhnyy Mar 17 '16 at 13:20
  • I think `find` needs to write to stdout. That's the key to explain the cases. And, I think needing to read from stdin may be another factor, though it's not in the above cases. – Robert Apr 27 '22 at 10:32

1 Answers1

1

I don't fully understand your question, but I'll try to explain the use of nohup:

From the manual page man nohup:

nohup - run a command immune to hangups, with output to a non-tty

So nohup disconnects the standard input and output streams from the terminal (/dev/null becomes input, output goes to file nohup.out) and also shields the application from SIGHUP signals (hangup signal). This allows you to terminate the shell process from which you started the nohup-ed command without killing this child process.


A similar way to prevent killing of a process when the parent shell gets terminated is disown:

my_command & disown

This runs my_command in background and disowns it from the parent process, but without performing any I/O redirection. It effectively makes the command an independent process, no longer being a child process of the parent shell.


When you only want to run a process in background, but don't want to disown it from the current shell (so that it will be killed when the parent process exits), you can omit the nohup or disown and only use Bash's & :

my_command &
Byte Commander
  • 105,631
  • 46
  • 284
  • 425