转自: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. 使用BeyondCompare比较文件夹下的文件时,相同的文件内容,但显示为不相同

    主要原因是: 两个文件行尾标题不一致而导致的,一个是PC,一个是Unix 解决办法: 随便比较文件夹中的两个文件,点击规则,去掉比较行尾(pc/mac/unix)选项,点击确认,回到文件夹比较界面,刷 ...

  2. Windows Xp不用安装软件管理多个远程桌面连接

    一直使用系统默认的Mstsc来进行远程连接,但如果要连接N个远程的话就比较麻烦 之前也找过第三方的管理软件如:mRemoteNG 此软件有优点就不说了,但我在使用此软件时有一个很大的问题,就是如果一个 ...

  3. SQLServer2008备份时发生无法打开备份设备

    如下图所示,在执行SQL一个简单的备份命令时发生下面的情况 问题分析: 1:可能是文件夹目录权限问题 2:可能是登录SQLServer服务器用户策略问题 于是就查看了E:\dw_backup的文件夹权 ...

  4. 图结构练习——BFS——从起始点到目标点的最短步数(邻接表+BFS)

    图练习-BFS-从起点到目标点的最短步数 Time Limit: 1000ms   Memory limit: 65536K  有疑问?点这里^_^ 题目描写叙述 在古老的魔兽传说中.有两个军团,一个 ...

  5. iOS 真机调试多台mac电脑共用一个证书

    大致流程:在你的开发电脑上导出一个 p12文件,以及在 apple开发者中心下载一个profile文件,把这两个文件导出给你的mac开发友就行了 打开 mac  钥匙工具-----找到你的证书---- ...

  6. 微信小程序 - 贝塞尔曲线(购物车效果)

    转载来源于:https://segmentfault.com/a/1190000011710786 简化了一下,发出来吧 示例源码:点击下载

  7. python发送邮件方法总结

    python中email模块使得处理邮件变得比较简单,今天着重学习了一下发送邮件的具体做法,这里写写自己的的心得,也请高手给些指点.     一.相关模块介绍 发送邮件主要用到了smtplib和ema ...

  8. Java之字节码(2) - .class文件格式详解

    转载来自 小介:去 年在读<深入解析JVM>的时候写的,记得当时还想着用自己的代码解析字节码的,最后只完成了一部分.现在都不知道还有没有保留着,貌似Apache有现 成的BCEL工程可以做 ...

  9. Wince6.0模拟器下载和使用方法

    原文地址:http://www.oogps.com/post/Wince6.0.html下载地址:Wince6.0模拟器下载.rar 第一步:把软件下载解压后看到以下目录. 第二步:双击运行上图中的S ...

  10. VC、OpenGL、ArcGIS Engine开发的二维三维结合的GIS系统

    一.前言 众所周知,二维GIS技术发展了近四十年,伴随着计算机软硬件以及关系型数据库的飞速发展,二维GIS技术已日臻完善.在对地理信息的分析功能上有着无可比拟的优势.一些宏观的地理信息,一维的地理信息 ...