[Linux内核]ctrl-z/fg/bg/nohup/setsid/()与&/disown/screen

转自:https://my.oschina.net/alphajay/blog/65058

My Tips:

Ctrl -z    ->   suspend

fg           ->   foreground

bg           ->  background

1. ctrl-z、fg、bg

如果前台执行一个程序很久没执行完,那么可以用 ctrl+z挂起它,系统会做类似如下提示:

1 [1]+  Stopped                 sleep 100

然后可以用bg把程序调到后台执行:

1 [root@lwy ~]# bg 1
2 [1]+ sleep 100 &

注:bg后加作业号(注释不是pid)

查看当前后台执行的进程状态:

1 [root@lwy ~]# jobs -l
2 [1]+ 10111 Running                 sleep 100 &

如果想调回前台,用fg+作业号:

1 [root@lwy ~]# fg 1
2 sleep 100

但是后台运行的程序还是会输出到屏幕上,会干扰工作,所以记得要重定向到一个文件中

2.关于Linux后台执行程序

以下摘自http://www.ibm.com/developerworks/cn/linux/l-cn-nohup/  其中有部分自己实践后修改。

原因:我们知道,当用户注销(logout)或者网络断开时,终端会收到 HUP(hangup)信号从而关闭其所有子进程。因此,我们的解决办法就有两种途径:要么让进程忽略 HUP 信号,要么让进程运行在新的会话里从而成为不属于此终端的子进程。

1. nohup

显而易见,nohup命令的功能是使进程忽略hangup信号,从而持续执行。nohup 的使用是十分方便的,只需在要处理的命令前加上 nohup 即可,标准输出和标准错误缺省会被重定向到 nohup.out 文件中。一般我们可在结尾加上"&"来将命令同时放入后台运行,也可用">filename 2>&1"来更改缺省的重定向文件名。

2. setsid

nohup 无疑能通过忽略 HUP 信号来使我们的进程避免中途被中断,但如果我们换个角度思考,如果我们的进程不属于接受 HUP 信号的终端的子进程,那么自然也就不会受到 HUP 信号的影响了。setsid 就能帮助我们做到这一点。setsid中的sid指的是session id,意指以该命令运行的进程是一个新的session,因此其父进程id不属于当前终端。实际上,setsid运行的进程,其父进程id(PPID)为1(init 进程的 PID)。

setsid 的使用也是非常方便的,也只需在要处理的命令前加上 setsid 即可。

实例:

 1 [root@lwy ~]# sleep 100 &
 2 [2] 10661
 3 [root@lwy ~]# ps -ef|grep sleep
 4 root     10661  9835  0 16:20 pts/1    00:00:00 sleep 100
 5 root     10663  9835  0 16:20 pts/1    00:00:00 grep sleep
 6 [root@lwy ~]# setsid sleep 100
 7 [root@lwy ~]# ps -ef|grep sleep
 8 root     10661  9835  0 16:20 pts/1    00:00:00 sleep 100
 9 root     10666     1  0 16:20 ?        00:00:00 sleep 100
10 root     10668  9835  0 16:20 pts/1    00:00:00 grep sleep

3. 括号()与&

我们知道,将一个或多个命名包含在“()”中就能让这些命令在子 shell 中运行中,从而扩展出很多有趣的功能,我们现在要讨论的就是其中之一。
当我们将"&"也放入“()”内之后,我们就会发现所提交的作业并不在作业列表中,也就是说,是无法通过jobs来查看的。让我们来看看为什么这样就能躲过 HUP 信号的影响吧。

本机实例:

1 [root@lwy ~]# (sleep 100 &)
2 [root@lwy ~]# ps -ef|grep sleep
3 root     10588     1  0 15:57 pts/1    00:00:00 sleep 100
4 root     10590  9835  0 15:57 pts/1    00:00:00 grep sleep
5 [root@lwy ~]# ps -p 9835   ##可以看出sleep 100 的父进程是当前shell终端
6 PID TTY          TIME CMD
7 9835 pts/1    00:00:00 bash

从上例中可以看出,新提交的进程的父 ID(PPID)为1(init 进程的 PID),并不是当前终端的进程 ID。因此并不属于当前终端的子进程,从而也就不会受到当前终端的 HUP 信号的影响了。

4. disown

如果我们未加任何处理就已经提交了命令,这时想加 nohup 或者 setsid 已经为时已晚,只能通过作业调度和 disown 来解决这个问题了。让我们来看一下 disown 的帮助信息:

 1 disown [-ar] [-h] [jobspec ...]
 2 Without options, each jobspec is  removed  from  the  table  of
 3 active  jobs.   If  the -h option is given, each jobspec is not
 4 removed from the table, but is marked so  that  SIGHUP  is  not
 5 sent  to the job if the shell receives a SIGHUP.  If no jobspec
 6 is present, and neither the -a nor the -r option  is  supplied,
 7 the  current  job  is  used.  If no jobspec is supplied, the -a
 8 option means to remove or mark all jobs; the -r option  without
 9 a  jobspec  argument  restricts operation to running jobs.  The
10 return value is 0 unless a jobspec does  not  specify  a  valid
11 job.

可以看出,我们可以用如下方式来达成我们的目的。

  • 用disown -h jobspec 来使某个作业忽略HUP信号。
  • 用disown -ah 来使所有的作业都忽略HUP信号。
  • 用disown -rh 来使正在运行的作业忽略HUP信号。

需要注意的是,当使用过 disown 之后,会将把目标作业从作业列表中移除,我们将不能再使用jobs来查看它,但是依然能够用ps -ef查找到它。
但是还有一个问题,这种方法的操作对象是作业,如果我们在运行命令时在结尾加了"&"来使它成为一个作业并在后台运行,那么就万事大吉了,我们可以通过jobs命令来得到所有作业的列表。但是如果并没有把当前命令作为作业来运行,如何才能得到它的作业号呢?答案就是用 CTRL-z(按住Ctrl键的同时按住z键)了!
CTRL-z 的用途就是将当前进程挂起(Suspend),然后我们就可以用jobs命令来查询它的作业号,再用bg jobspec 来将它放入后台并继续运行。需要注意的是,如果挂起会影响当前进程的运行结果,慎用此方法。

CTRL-z小tips

在我们的日常工作中,我们可以用 CTRL-z 来将当前进程挂起到后台暂停运行,执行一些别的操作,然后再用 fg 来将挂起的进程重新放回前台(也可用 bg 来将挂起的进程放在后台)继续运行。这样我们就可以在一个终端内灵活切换运行多个任务,这一点在调试代码时尤为有用。因为将代码编辑器挂起到后台再重新放回时,光标定位仍然停留在上次挂起时的位置,避免了重新定位的麻烦。


示例:

1 [root@lwy ~]# sleep 100 &
2 [1] 10895
3 [root@lwy ~]# jobs
4 [1]+  Running                 sleep 100 &
5 [root@lwy ~]# disown -h %1
6 [root@lwy ~]# ps -ef|grep sleep
7 root     10895  9835  0 17:04 pts/1    00:00:00 sleep 100
8 root     10898  9835  0 17:04 pts/1    00:00:00 grep sleep

此时退出终端也无妨,因为此进程已不接受任何HUP信号。

给自己的小tips:才知道kill %[作业号] 也可以杀进程= =。。。当然仅限在作业队列中有作业号的进程。

1 [root@lwy ~]# ps -ef|grep sleep
2 root     10528  9835  0 15:50 pts/1    00:00:00 sleep 200
3 root     10846  9835  0 16:59 pts/1    00:00:00 grep sleep
4 [root@lwy ~]# kill %1
5 [1]+  已终止               sleep 200

5.screen

具体可以参看《screen》:http://tec110505.diandian.com/post/2012-03-28/14742085

我们已经知道了如何让进程免受 HUP 信号的影响,但是如果有大量这种命令需要在稳定的后台里运行,如何避免对每条命令都做这样的操作呢

此时最方便的方法就是 screen 了。简单的说,screen 提供了 ANSI/VT100 的终端模拟器,使它能够在一个真实终端下运行多个全屏的伪终端。screen 的参数很多,具有很强大的功能,我们在此仅介绍其常用功能以及简要分析一下为什么使用 screen 能够避免 HUP 信号的影响。我们先看一下 screen 的帮助信息:

 1 SCREEN(1)                                                           SCREEN(1)
 2 
 3 NAME
 4        screen - screen manager with VT100/ANSI terminal emulation
 5 
 6 SYNOPSIS
 7        screen [ -options ] [ cmd [ args ] ]
 8        screen -r [[pid.]tty[.host]]
 9        screen -r sessionowner/[[pid.]tty[.host]]
10 
11 DESCRIPTION
12        Screen  is  a  full-screen  window manager that multiplexes a physical
13        terminal between several  processes  (typically  interactive  shells).
14        Each  virtual  terminal provides the functions of a DEC VT100 terminal
15        and, in addition, several control functions from the  ISO  6429  (ECMA
16        48,  ANSI  X3.64)  and ISO 2022 standards (e.g. insert/delete line and
17        support for multiple character sets).  There is a  scrollback  history
18        buffer  for  each virtual terminal and a copy-and-paste mechanism that
19        allows moving text regions between windows.

使用 screen 很方便,有以下几个常用选项:

  • 用screen -dmS session_name来建立一个处于断开模式下的会话(并指定其会话名)。
  • 用screen -list($screen -ls)来列出所有会话。
  • 用screen -r session_name来重新连接指定会话。
  • 用快捷键CTRL+a d来暂时断开当前会话。

本机实例

1 [root@lwy  ~]# screen -dmS test
2 [root@lwy  ~]# screen -list
3 There is a screen on:
4 10811.test      (Detached)
5 1 Socket in /var/run/screen/S-root.
6 [root@lwy  ~]# screen -r test

当我们用“-r”连接到 screen 会话后,我们就可以在这个伪终端里面为所欲为,再也不用担心 HUP 信号会对我们的进程造成影响,也不用给每个命令前都加上“nohup”或者“setsid”了。这是为什么呢?让我来看一下下面两个例子吧。

1. 未使用 screen 时新进程的进程树

 1 [root@lwy  ~]# sleep 200 &
 2 [1] 10932
 3 [root@lwy  ~]# pstree -H 10932
 4 init─┬─acpid
 5      ├─atd
 6      ├─auditd─┬─audispd───{audispd}
 7      │        └─{auditd}
 8      ├─automount───4*[{automount}]
 9      ├─avahi-daemon───avahi-daemon
10      ├─crond
11      ├─cupsd
12      ├─dbus-daemon
13      ├─events/0
14      ├─events/1
15      ├─gam_server
16      ├─gpm
17      ├─hald───hald-runner───hald-addon-acpi
18      ├─hcid
19      ├─hidd
20      ├─httpd───11*[httpd]
21      ├─khelper
22      ├─klogd
23      ├─krfcommd
24      ├─ksoftirqd/0
25      ├─ksoftirqd/1
26      ├─kthread─┬─aio/0
27      │         ├─aio/1
28      │         ├─ata/0
29      │         ├─ata/1
30      │         ├─ata_aux
31      │         ├─cqueue/0
32      │         ├─cqueue/1
33      │         ├─kacpid
34      │         ├─kauditd
35      │         ├─kblockd/0
36      │         ├─kblockd/1
37      │         ├─kedac
38      │         ├─khubd
39      │         ├─3*[kjournald]
40      │         ├─kmpathd/0
41      │         ├─kmpathd/1
42      │         ├─kpsmoused
43      │         ├─kseriod
44      │         ├─kswapd0
45      │         ├─2*[pdflush]
46      │         ├─scsi_eh_0
47      │         └─scsi_eh_1
48      ├─login_keepalive
49      ├─loop0
50      ├─migration/0
51      ├─migration/1
52      ├─6*[mingetty]
53      ├─pcscd───{pcscd}
54      ├─portmap
55      ├─rpc.idmapd
56      ├─rpc.statd
57      ├─2*[sendmail]
58      ├─sh───mysqld───15*[{mysqld}]
59      ├─smartd
60      ├─snmpd───{snmpd}
61      ├─sshd───sshd───bash─┬─pstree
62      │                    └─sleep├─svnserve
63      ├─syslogd
64      ├─udevd
65      ├─watchdog/0
66      ├─watchdog/1
67      ├─xfs
68      ├─xinetd
69      └─yum-updatesd

我们可以看出,未使用 screen 时我们所处的 bash 是 sshd 的子进程,当 ssh 断开连接时,HUP 信号自然会影响到它下面的所有子进程(包括我们新建立的 ping 进程)。

2. 使用了 screen 后新进程的进程树

 1 [root@lwy  ~]# sleep 100 &
 2 [1] 10956
 3 [root@lwy  ~]# pstree -H 108956
 4 init─┬─acpid
 5      ├─atd
 6      ├─auditd─┬─audispd───{audispd}
 7      │        └─{auditd}
 8      ├─automount───4*[{automount}]
 9      ├─avahi-daemon───avahi-daemon
10      ├─crond
11      ├─cupsd
12      ├─dbus-daemon
13      ├─events/0
14      ├─events/1
15      ├─gam_server
16      ├─gpm
17      ├─hald───hald-runner───hald-addon-acpi
18      ├─hcid
19      ├─hidd
20      ├─httpd───11*[httpd]
21      ├─krfcommd
22      ├─ksoftirqd/0
23      ├─ksoftirqd/1
24      ├─kthread─┬─aio/0
25      │         ├─aio/1
26      │         ├─ata/0
27      │         ├─ata/1
28      │         ├─ata_aux
29      │         ├─cqueue/0
30      │         ├─cqueue/1
31      │         ├─kacpid
32      │         ├─kauditd
33      │         ├─kblockd/0
34      │         ├─kblockd/1
35      │         ├─kedac
36      │         ├─khubd
37      │         ├─3*[kjournald]
38      │         ├─kmpathd/0
39      │         ├─kmpathd/1
40      │         ├─kpsmoused
41      │         ├─kseriod
42      │         ├─kswapd0
43      │         ├─2*[pdflush]
44      │         ├─scsi_eh_0
45      │         └─scsi_eh_1
46      ├─login_keepalive
47      ├─loop0
48      ├─migration/0
49      ├─migration/1
50      ├─6*[mingetty]
51      ├─pcscd───{pcscd}
52      ├─portmap
53      ├─rpc.idmapd
54      ├─rpc.statd
55      ├─screen───bash─┬─pstree
56      │               └─sleep├─2*[sendmail]
57      ├─sh───mysqld───15*[{mysqld}]
58      ├─smartd
59      ├─snmpd───{snmpd}
60      ├─sshd───sshd───bash─┬─screen
61      │                    └─sleep
62      ├─svnserve
63      ├─syslogd
64      ├─udevd
65      ├─watchdog/0
66      ├─watchdog/1
67      ├─xfs
68      ├─xinetd
69      └─yum-updatesd

而使用了 screen 后就不同了,此时 bash 是 screen 的子进程,而 screen 是 init(PID为1)的子进程。那么当 ssh 断开连接时,HUP 信号自然不会影响到 screen 下面的子进程了。

总结

现在几种方法已经介绍完毕,我们可以根据不同的场景来选择不同的方案。nohup/setsid 无疑是临时需要时最方便的方法,disown 能帮助我们来事后补救当前已经在运行了的作业,而 screen 则是在大批量操作时不二的选择了。 

Bg, Fg, &, Ctrl-Z – 5 Examples to Manage Unix Background Jobs

http://www.thegeekstuff.com/2010/05/unix-background-job/

When you execute a unix shell-script or command that takes a long time, you can run it as a background job.

In this article, let us review how to execute a job in the background, bring a job to the foreground, view all background jobs, and kill a background job.

1. Executing a background job

Appending an ampersand ( & ) to the command runs the job in the background.

For example, when you execute a find command that might take a lot time to execute, you can put it in the background as shown below. Following example finds all the files under root file system that changed within the last 24 hours.

1 # find / -ctime -1 > /tmp/changed-file-list.txt &

2. Sending the current foreground job to the background using CTRL-Z and bg command

You can send an already running foreground job to background as explained below:

  • Press ‘CTRL+Z’ which will suspend the current foreground job.
  • Execute bg to make that command to execute in background.

For example, if you’ve forgot to execute a job in a background, you don’t need to kill the current job and start a new background job. Instead, suspend the current job and put it in the background as shown below.

1 # find / -ctime -1 > /tmp/changed-file-list.txt
2 
3 # [CTRL-Z]
4 [2]+  Stopped                 find / -ctime -1 > /tmp/changed-file-list.txt
5 
6 # bg 

3. View all the background jobs using jobs command

You can list out the background jobs with the command jobs. Sample output of jobs command is

1 # jobs
2 [1]   Running                 bash download-file.sh &
3 [2]-  Running                 evolution &
4 [3]+  Done                    nautilus .

4. Taking a job from the background to the foreground using fg command

You can bring a background job to the foreground using fg command. When executed without arguments, it will take the most recent background job to the foreground.

# fg

If you have multiple background ground jobs, and would want to bring a certain job to the foreground, execute jobs command which will show the job id and command.

In the following example, fg %1 will bring the job#1 (i.e download-file.sh) to the foreground.

1 # jobs
2 [1]   Running                 bash download-file.sh &
3 [2]-  Running                 evolution &
4 [3]+  Done                    nautilus .
5 
6 # fg %1

5. Kill a specific background job using kill %

If you want to kill a specific background job use, kill %job-number. For example, to kill the job 2 use

1 # kill %2

To kill a foreground jobs, use one of the methods specified in our earlier article 4 Ways to Kill a Process — kill, killall, pkill, xkill.

原文地址:https://www.cnblogs.com/aaronLinux/p/6345072.html