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

My Tips:

Ctrl -z    ->   suspend

fg           ->   foreground

bg           ->  background

1. ctrl-z、fg、bg

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

 []+  Stopped                 sleep 

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

 [root@lwy ~]# bg
[]+ sleep &

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

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

 [root@lwy ~]# jobs -l
[]+ Running sleep &

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

 [root@lwy ~]# fg
sleep

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

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 即可。

实例:

 [root@lwy ~]# sleep  &
[]
[root@lwy ~]# ps -ef|grep sleep
root : pts/ :: sleep
root : pts/ :: grep sleep
[root@lwy ~]# setsid sleep
[root@lwy ~]# ps -ef|grep sleep
root : pts/ :: sleep
root : ? :: sleep
root : pts/ :: grep sleep

3. 括号()与&

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

本机实例:

 [root@lwy ~]# (sleep  &)
[root@lwy ~]# ps -ef|grep sleep
root : pts/ :: sleep
root : pts/ :: grep sleep
[root@lwy ~]# ps -p ##可以看出sleep 的父进程是当前shell终端
PID TTY TIME CMD
pts/ :: bash

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

4. disown

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

 disown [-ar] [-h] [jobspec ...]
Without options, each jobspec is removed from the table of
active jobs. If the -h option is given, each jobspec is not
removed from the table, but is marked so that SIGHUP is not
sent to the job if the shell receives a SIGHUP. If no jobspec
is present, and neither the -a nor the -r option is supplied,
the current job is used. If no jobspec is supplied, the -a
option means to remove or mark all jobs; the -r option without
a jobspec argument restricts operation to running jobs. The
return value is unless a jobspec does not specify a valid
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 来将挂起的进程放在后台)继续运行。这样我们就可以在一个终端内灵活切换运行多个任务,这一点在调试代码时尤为有用。因为将代码编辑器挂起到后台再重新放回时,光标定位仍然停留在上次挂起时的位置,避免了重新定位的麻烦。

示例:

 [root@lwy ~]# sleep  &
[]
[root@lwy ~]# jobs
[]+ Running sleep &
[root@lwy ~]# disown -h %
[root@lwy ~]# ps -ef|grep sleep
root : pts/ :: sleep
root : pts/ :: grep sleep

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

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

 [root@lwy ~]# ps -ef|grep sleep
root : pts/ :: sleep
root : pts/ :: grep sleep
[root@lwy ~]# kill %
[]+ 已终止 sleep

5.screen

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

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

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

 SCREEN()                                                           SCREEN()

 NAME
screen - screen manager with VT100/ANSI terminal emulation SYNOPSIS
screen [ -options ] [ cmd [ args ] ]
screen -r [[pid.]tty[.host]]
screen -r sessionowner/[[pid.]tty[.host]] DESCRIPTION
Screen is a full-screen window manager that multiplexes a physical
terminal between several processes (typically interactive shells).
Each virtual terminal provides the functions of a DEC VT100 terminal
and, in addition, several control functions from the ISO (ECMA
, ANSI X3.) and ISO standards (e.g. insert/delete line and
support for multiple character sets). There is a scrollback history
buffer for each virtual terminal and a copy-and-paste mechanism that
allows moving text regions between windows.

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

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

本机实例

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

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

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

 [root@lwy  ~]# sleep  &
[]
[root@lwy ~]# pstree -H
init─┬─acpid
├─atd
├─auditd─┬─audispd───{audispd}
│ └─{auditd}
├─automount───*[{automount}]
├─avahi-daemon───avahi-daemon
├─crond
├─cupsd
├─dbus-daemon
├─events/
├─events/
├─gam_server
├─gpm
├─hald───hald-runner───hald-addon-acpi
├─hcid
├─hidd
├─httpd───*[httpd]
├─khelper
├─klogd
├─krfcommd
├─ksoftirqd/
├─ksoftirqd/
├─kthread─┬─aio/
│ ├─aio/
│ ├─ata/
│ ├─ata/
│ ├─ata_aux
│ ├─cqueue/
│ ├─cqueue/
│ ├─kacpid
│ ├─kauditd
│ ├─kblockd/
│ ├─kblockd/
│ ├─kedac
│ ├─khubd
│ ├─*[kjournald]
│ ├─kmpathd/
│ ├─kmpathd/
│ ├─kpsmoused
│ ├─kseriod
│ ├─kswapd0
│ ├─*[pdflush]
│ ├─scsi_eh_0
│ └─scsi_eh_1
├─login_keepalive
├─loop0
├─migration/
├─migration/
├─*[mingetty]
├─pcscd───{pcscd}
├─portmap
├─rpc.idmapd
├─rpc.statd
├─*[sendmail]
├─sh───mysqld───*[{mysqld}]
├─smartd
├─snmpd───{snmpd}
61 ├─sshd───sshd───bash─┬─pstree
62 │ └─sleep├─svnserve
├─syslogd
├─udevd
├─watchdog/
├─watchdog/
├─xfs
├─xinetd
└─yum-updatesd

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

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

 [root@lwy  ~]# sleep  &
[]
[root@lwy ~]# pstree -H
init─┬─acpid
├─atd
├─auditd─┬─audispd───{audispd}
│ └─{auditd}
├─automount───*[{automount}]
├─avahi-daemon───avahi-daemon
├─crond
├─cupsd
├─dbus-daemon
├─events/
├─events/
├─gam_server
├─gpm
├─hald───hald-runner───hald-addon-acpi
├─hcid
├─hidd
├─httpd───*[httpd]
├─krfcommd
├─ksoftirqd/
├─ksoftirqd/
├─kthread─┬─aio/
│ ├─aio/
│ ├─ata/
│ ├─ata/
│ ├─ata_aux
│ ├─cqueue/
│ ├─cqueue/
│ ├─kacpid
│ ├─kauditd
│ ├─kblockd/
│ ├─kblockd/
│ ├─kedac
│ ├─khubd
│ ├─*[kjournald]
│ ├─kmpathd/
│ ├─kmpathd/
│ ├─kpsmoused
│ ├─kseriod
│ ├─kswapd0
│ ├─*[pdflush]
│ ├─scsi_eh_0
│ └─scsi_eh_1
├─login_keepalive
├─loop0
├─migration/
├─migration/
├─*[mingetty]
├─pcscd───{pcscd}
├─portmap
├─rpc.idmapd
├─rpc.statd
55 ├─screen───bash─┬─pstree
56 │ └─sleep├─2*[sendmail]
├─sh───mysqld───*[{mysqld}]
├─smartd
├─snmpd───{snmpd}
├─sshd───sshd───bash─┬─screen
│ └─sleep
├─svnserve
├─syslogd
├─udevd
├─watchdog/
├─watchdog/
├─xfs
├─xinetd
└─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.

 # find / -ctime - > /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.

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

 # [CTRL-Z]
[]+ Stopped find / -ctime - > /tmp/changed-file-list.txt # 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

 # jobs
[] Running bash download-file.sh &
[]- Running evolution &
[]+ 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.

 # jobs
[] Running bash download-file.sh &
[]- Running evolution &
[]+ Done nautilus . # fg %

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

 # kill %

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.

[Linux内核]ctrl-z/fg/bg/nohup/setsid/()与&/disown/screen的更多相关文章

  1. ctrl + z fg bg

    [root@bass ~]# jobs [1]+ Stopped vncviewer 192.168.1.17:5904 [root@bass ~]# #ctrl + z [root@bass ~]# ...

  2. Centos安装自定义布局才能自己划分各个区的大小ctrl+z ,fg ,route -n ,cat !$ ,!cat ,XShell 设置, ifconfig CentOS远程连接 Linux中的输入流 第一节课

    Centos安装自定义布局才能自己划分各个区的大小ctrl+z ,fg ,route -n ,cat !$ ,!cat ,XShell 设置, ifconfig  CentOS远程连接  Linux中 ...

  3. Linux中ctrl+z 、ctrl+c、 ctrl+d区别

    Ctrl + C 和Ctrl + Z都是中断命令,但是他们的作用却不一样. Ctrl + C 是强制中断程序的执行,进程已经终止. Ctrl + C 发送 SIGINT信号 参考:linux信号 Ct ...

  4. linux 后台运行进程 fg bg ctrl+z nohup

    fg.bg.jobs.&.nohup.ctrl+z.ctrl+c 命令 一.& 加在一个命令的最后,可以把这个命令放到后台执行,如 watch -n 10 sh test.sh &am ...

  5. Linux中切换前后台命令:ctrl+z,bg,fg,jobs

    一.运行某些服务的时候,我希望切换到后台运行: 两种方法: 1.可以在运行的时候,在启动服务命令的最后面加一个字符&,例如 ./serviceStart & 2.在服务启动后,按ctr ...

  6. Linux - 后台运行 ctrl + z , jobs , bg , fg

    一.& 最经常被用到 这个用在一个命令的最后,可以把这个命令放到后台执行 二.ctrl + z 可以将一个正在前台执行的命令放到后台,并且暂停三.jobs查看当前有多少在后台运行的命令四.fg ...

  7. Linux必须会的命令---也是以前记录的,ctrl+z fg 啥的 jobs 比较实用

    fg.bg.jobs.&.ctrl + z都是跟系统任务有关的,虽然现在基本上不怎么需要用到这些命令,但学会了也是很实用的 一.& 最经常被用到 这个用在一个命令的最后,可以把这个命令 ...

  8. linux中ctrl+z、ctrl+d和ctrl+c的区别

    ctrl+c和ctrl+z都是中断命令,但是他们的作用却不一样.ctrl+c是强制中断程序的执行,而ctrl+z的是将任务中断,但是此任务并没有结束,他仍然在进程中他只是维持挂起的状态,用户可以使用f ...

  9. Linux中ctrl+z 、ctrl+c、 ctrl+d区别

    ctrl+c,ctrl+d,ctrl+z在linux程序中意义和区别 ctrl+c和ctrl+z都是中断命令,但是他们的作用却不一样.   ctrl+c是强制中断程序的执行,,进程已经终止.   ct ...

随机推荐

  1. Jquery chosen动态设置值 select Ajax动态载入数据 设置chosen和获取他们选中的值

      在做一个编辑对话框时,要对里面带有select option的操作.主要是想动态载入option和对option的选中.可是由于项目中使用了jquery里的chosen()方法.怎么也无法实现效果 ...

  2. GDALOpen 代码分析

    先来一句话,看了这么多GDAL的源代码,并不喜欢其C风格的烙印太重,还是更喜欢boost风格的简洁的现代C++风格.不过为了更好地应用GDAL,更深的定制它,还是需要将源代码看到底.因为GDAL毕竟是 ...

  3. Python 高级图像处理

    构建图像搜索引擎并不是一件容易的任务.这里有几个概念.工具.想法和技术需要实现.主要的图像处理概念之一是逆图像查询(RIQ).Google.Cloudera.Sumo Logic 和 Birst 等公 ...

  4. html5-video视频播放

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/ ...

  5. 【CODEFORCES】 A. Keyboard

    A. Keyboard time limit per test 2 seconds memory limit per test 256 megabytes input standard input o ...

  6. 查看慢sql语句

    查看慢sql语句 st.text AS SQL_Full --父级完整语句 ,) , ((CASE statement_end_offset THEN DATALENGTH(st.text) ELSE ...

  7. linux动态链接库导出函数控制

    windows 环境的vc的话,可以方便的指定__declspec(dllexport) 关键字来控制是否把dll中的函数导出.我也来测试一下linux下面是如何做的:先看gcc 和ld的相关选项 = ...

  8. 深入RecyclerView-为什么要使用ItemDecoration

    Part 1:不要用view做分割线 首先,什么是ItemDecoration?来看看官网是如何解释的. ItemDecoration允许从adapter的数据集合中为特定的item视图添加特性的绘制 ...

  9. script标签的crossorigin属性

    通常我们使用window.onerror来捕获js脚本的错误信息. 但是对于跨域调用的js脚本,onerror事件只会给出很少的报错信息:error: Script error. 这个简单的信息很明显 ...

  10. Javascript中的对象和原型(一)(转载)

    面向对象的语言(如Java)中有类的概念,而通过类可以创建任意多个具有相同属性和方法的对象.但是,JavaScript 没有类的概念,因此它的对象也与基于类的语言中的对象有所不同. 要了解面向对象,首 ...