linux execute in background

link

Problem

Always meet problem like this:
Login in by telnet/ssh, run some time costs task
But be interrupted, cause by the net problem.

How to deal this kind problem, let task run background

Command nohup/setsid/&

  1. nohup

in early version UNIX terminal communicate with system by
modem[cat?]. when logout or disconnect, modem send a hang up
signal to system to close current session process and all sub processes.

When terminal logout or connect broke, terminal recieves a ‘HUP[hangup]’ signal.
So we have two solutions

  • let process ignore ‘HUP’ signal
  • change process’s owner
1
2
nohup ./sunny.sh clientid xxxxx &
nohup ./sunny.sh clientid > sunny.log 2>&1 &
  1. setsid

Change process’s owner to process id ‘1’

1
setid ./sunny.sh clientid xxxxx
  1. &

When command put in () , command can be run in sub shell.
Put & into () as well, the commited job wouldn’t be add in job list.
So command can ignore the HUP

1
(./sunny.sh clientid xxxxx &)
  1. disown

If a process already running

  • disown -h make a job ignore signal
  • disown -ah make all jobs ignore signal
  • disown -rh make running jobs ignore signal

if job already run in background

1
2
3
4
5
6
7
./sunny.sh clientid xxxxx &

[1]+ Running ./sunny.sh clientid xxxxx &

disown -h %1

ps -ef |grep sunny

if job already run in front

1
2
3
4
5
6
7
8
9
10
11
12
./sunny.sh clientid xxxxx

# [ctrl + z]
[1]+ Stopped ./sunny.sh clientid xxxxx

# put to background
bg %1
[1]+ Running ./sunny.sh clientid xxxxx &

disown -h %1

ps -ef |grep sunny