如何在Linux上运行和控制后台进程

A shell environment on a Linux computer.
Fatmawati Achmad Zaenuri/Shutterstock.com Fatmawati Achmad Zaenuri / Shutterstock.com

Use the Bash shell in Linux to manage foreground and background processes. You can use Bash’s job control functions and signals to give you more flexibility in how you run commands. We show you how.

在Linux中使用Bash Shell管理前台和后台进程。 您可以使用Bash的作业控制功能和信号为您提供运行命令的更多灵活性。 我们向您展示如何。

所有关于流程 (All About Processes)

Whenever a program is executed in a Linux or Unix-like operating system, a process is started. “Process” is the name for the internal representation of the executing program in the computer’s memory.  There is a process for every active program. In fact, there is a process for nearly everything that is running on your computer. That includes the components of your graphical desktop environment (GDE) such as GNOME or KDE, and system daemons that are launched at start-up.

每当在Linux或类Unix操作系统中执行程序时,都会启动一个进程。 “进程”是计算机内存中正在执行的程序的内部表示形式的名称。 每个活动程序都有一个过程。 实际上,几乎所有正在计算机上运行的进程都有一个过程。 其中包括图形桌面环境 (GDE)的组件,例如GNOMEKDE ,以及在启动时启动的系统守护程序

Why nearly everything that is running? Well, Bash built-ins such as cd, pwd, and alias do not need to have a process launched (or “spawned”) when they are run. Bash executes these commands within the instance of the Bash shell that is running in your terminal window. These commands are fast precisely because they don’t need to have a process launched for them to execute. (You can type help in a terminal window to see the list of Bash built-ins.)

为什么几乎所有东西都在运行? 好吧,Bash内置程序(例如cdpwdalias )在运行时无需启动(或“生成”)进程。 Bash在您的终端窗口中运行的Bash Shell实例中执行这些命令。 这些命令之所以快速是因为它们不需要启动进程即可执行。 (您可以在终端窗口中键入help来查看Bash内置组件的列表。)

Processes can be running in the foreground, in which case they take over your terminal until they have completed, or they can be run in the background. Processes that run in the background don’t dominate the terminal window and you can continue to work in it. Or at least, they don’t dominate the terminal window if they don’t generate screen output.

进程可以在前台运行,在这种情况下,它们将接管您的终端直到完成为止,或者可以在后台运行。 在后台运行的进程不会主导终端窗口,您可以继续在其中运行。 或者至少,如果它们不生成屏幕输出,它们就不会控制终端窗口。

凌乱的例子 (A Messy Example)

We’ll start a simple ping trace running. We’re going to ping the How-To Geek domain. This will execute as a foreground process.

我们将开始运行一个简单的ping 跟踪 。 我们将对How-To Geek域进行ping操作。 这将作为前台进程执行。

ping www.howtogeek.com
ping www.howtogeek.com in a terminal window

We get the expected results, scrolling down the terminal window. We can’t do anything else in the terminal window while ping is running. To terminate the command hit Ctrl+C.

在终端窗口下滚动,我们得到了预期的结果。 ping运行时,我们无法在终端窗口中执行任何其他操作。 要终止命令,请Ctrl+C

Ctrl+C
ping trace output in a terminal window

The visible effect of the Ctrl+C is highlighted in the screenshot. ping gives a short summary and then stops.

截图中突出显示了Ctrl+C的可见效果。 ping提供简短摘要,然后停止。

Let’s repeat that. But this time we’ll hit Ctrl+Z instead of Ctrl+C. The task won’t be terminated. It will become a background task. We get control of the terminal window returned to us.

让我们重复一遍。 但是这次我们将按Ctrl+Z而不是Ctrl+C 任务不会终止。 这将成为后台任务。 我们可以控制返回给我们的终端窗口。

ping www.howtogeek.com
Ctrl+Z
effect of Ctrl+Z on a command running in a terminal window

The visible effect of hitting Ctrl+Z is highlighted in the screenshot.

屏幕截图中突出显示了Ctrl+Z的可见效果。

This time we are told the process is stopped. Stopped doesn’t mean terminated. It’s like a car at a stop sign. We haven’t scrapped it and thrown it away. It’s still on the road, stationary, waiting to go. The process is now a background job.

这次我们被告知该过程已停止。 停止并不意味着终止。 就像汽车在停车标志。 我们还没有废弃它并把它扔掉。 它仍然在路上,静止不动,等待驶去。 现在,该过程是一项后台工作

The jobs command will list the jobs that have been started in the current terminal session. And because jobs are (inevitably) processes, we can also use the ps command to see them. Let’s use both commands and compare their outputs. We’ll use the T option (terminal) option to only list the processes that are running in this terminal window. Note that there is no need to use a hyphen - with the T option.

jobs命令将列出在当前终端会话中已启动的作业 。 由于作业是(不可避免的)进程,因此我们也可以使用ps命令查看它们。 让我们使用这两个命令并比较它们的输出。 我们将使用T选项(终端)选项仅列出在此终端窗口中运行的进程。 请注意,无需使用连字符-带有T选项。

jobs
ps T
jobs command in a terminal window

The jobs command tells us:

jobs命令告诉我们:

  • [1]: The number in square brackets is the job number. We can use this to refer to the job when we need to control it with job control commands.

    [1] :方括号中的数字是作业编号。 当需要通过作业控制命令控制作业时,可以使用它来引用作业。

  • +: The plus sign + shows that this is the job that will be acted upon if we use a job control command without a specific job number. It is called the default job. The default job is always the one most recently added to the list of jobs.

    + :加号+表示如果我们使用没有特定作业编号的作业控制命令,则将执行此作业。 这称为默认作业。 默认作业始终是最近添加到作业列表中的作业。

  • Stopped: The process is not running.

    已停止 :进程未运行。

  • ping www.howtogeek.com: The command line that launched the process.

    ping www.howtogeek.com :启动该过程的命令行。

The ps command tells us:

ps命令告诉我们:

  • PID: The process ID of the process. Each process has a unique ID.

    PID :进程的进程ID。 每个进程都有一个唯一的ID。

  • TTY: The pseudo-teletype (terminal window) that the process was executed from.

    TTY :执行过程的伪teletype(终端窗口)。

  • STAT: The status of the process.

    STAT :进程的状态。

  • TIME: The amount of CPU time consumed by the process.

    TIME :进程消耗的CPU时间。

  • COMMAND: The command that launched the process.

    COMMAND :启动进程的命令。

These are common values for the STAT column:

这些是STAT列的常用值:

  • D: Uninterruptible sleep. The process is in a waiting state, usually waiting for input or output, and cannot be interrupted.

    D :不间断的睡眠。 进程处于等待状态,通常等待输入或输出,并且不能中断。

  • I: Idle.

    :空闲。

  • R: Running.

    R :跑步。

  • S: Interruptible sleep.

    S :睡眠中断。

  • T: Stopped by a job control signal.

    T :由作业控制信号停止。

  • Z: A zombie process. The process has been terminated but hasn’t been “cleaned down” by its parent process.

    Z :僵尸进程。 该进程已终止,但尚未被其父进程“清理”。

The value in the STAT column can be followed by one of these extra indicators:

STAT列中的值之后可以是以下这些额外指示符之一:

  • <: High-priority task (not nice to other processes).

    < :高优先级任务(不适用于其他进程)。

  • N: Low-priority (nice to other processes).

    N :低优先级(对其他进程不利)。

  • L: process has pages locked into memory (typically used by real-time processes).

    L :进程将页面锁定到内存中(通常由实时进程使用)。

  • s: A session leader. A session leader is a process that has launched process groups. A shell is a session leader.

    s :会议负责人。 会话负责人是启动了流程组的流程。 Shell是会话负责人。

  • l: Multi-thread process.

    l :多线程进程。

  • +: A foreground process.

    + :前台进程。

We can see that Bash has a state of Ss. The uppercase “S” tell us the Bash shell is sleeping, and it is interruptible. As soon as we need it, it will respond.  The lowercase “s” tells us that the shell is a session leader.

我们可以看到Bash的状态为Ss 。 大写的“ S”告诉我们Bash shell正在Hibernate,并且可以中断。 只要我们需要它,它就会响应。 小写的“ s”告诉我们外壳程序是会话领导者。

The ping command has a state of T. This tells us that ping has been stopped by a job control signal. In this example, that was the Ctrl+Z we used to put it into the background.

ping命令的状态为T 这表明我们已通过作业控制信号停止了ping操作。 在此示例中,这就是我们用来将其放入背景的Ctrl+Z

The ps T command has a state of R, which stands for running. The + indicates that this process is a member of the foreground group. So the ps T command is running in the foreground.

ps T命令的状态为R ,表示运行。 +表示此进程是前台组的成员。 因此ps T命令在前台运行。

bg命令 (The bg Command)

The bg command is used to resume a background process. It can be used with or without a job number. If you use it without a job number the default job is brought to the foreground. The process still runs in the background. You cannot send any input to it.

bg命令用于恢复后台进程。 可以使用或不使用工作编号。 如果您在没有工作编号的情况下使用它,则会将默认工作置于前台。 该过程仍在后台运行。 您无法向其发送任何输入。

If we issue the bg command, we will resume our ping command:

如果发出bg命令,将恢复ping命令:

bg
bg in a terminal window

The ping command resumes and we see the scrolling output in the terminal window once more. The name of the command that has been restarted is displayed for you. This is highlighted in the screenshot.

ping命令继续,我们将再次在终端窗口中看到滚动输出。 将显示为您重新启动的命令的名称。 这在屏幕截图中突出显示。

resumed ping background process with output in a terminal widow

But we have a problem. The task is running in the background and won’t accept input. So how do we stop it? Ctrl+C doesn’t do anything. We can see it when we type it but the background task doesn’t receive those keystrokes so it keeps pinging merrily away.

但是我们有一个问题。 该任务在后台运行,并且不接受输入。 那么我们如何制止它? Ctrl+C不会执行任何操作。 当我们键入它时我们可以看到它,但是后台任务没有收到这些按键,因此它会持续快速发送。

Background task ignoring Ctrl+C in a terminal window

In fact, we’re now in a strange blended mode. We can type in the terminal window but what we type is quickly swept away by the scrolling output from the ping command. Anything we type takes effect in the foregound.

实际上,我们现在处于一种奇怪的混合模式。 我们可以在终端窗口中键入内容,但是ping命令的滚动输出会Swift将所键入的内容清除掉。 我们键入的任何内容都会在前项中生效。

To stop our background task we need to bring it to the foreground and then stop it.

要停止后台任务,我们需要将其放到前台,然后再停止它。

fg命令 (The fg Command)

The fg command will bring a background task into the foreground. Just like the bg command, it can be used with or without a job number. Using it with a job number means it will operate on a specific job. If it is used without a job number the last command that was sent to the background is used.

fg命令会将后台任务置于前台。 就像bg命令一样,它可以与作业编号一起使用,也可以不与作业编号一起使用。 将其与作业编号一起使用意味着它将在特定作业上运行。 如果不使用作业号使用该命令,则使用发送到后台的最后一个命令。

If we type fg our ping command will be brought to the foreground. The characters we type are mixed up with the output from the ping command, but they are operated on by the shell as if they had been entered on the command line as usual. And in fact, from the Bash shell’s point of view, that is exactly what has happened.

如果我们输入fg我们的ping命令将被带到前台。 我们键入的字符与ping命令的输出混合在一起,但是它们会像通常在命令行上输入的一样,由shell进行操作。 实际上,从Bash shell的角度来看,这就是发生的事情。

fg
fg command mixed in with the output from ping in a terminal window

And now that we have the ping command running in the foreground once more, we can use Ctrl+C to kill it.

现在,我们再次在前台运行了ping命令,我们可以使用Ctrl+C杀死它。

Ctrl+C
Ctrl+C stopping the ping command in a terminal window

我们需要发出正确的信号 (We Need to Send the Right Signals)

That wasn’t exactly pretty. Evidently running a process in the background works best when the process doesn’t produce output and doesn’t require input.

那不是很漂亮。 当进程不产生输出且不需要输入时,显然在后台运行该进程最为有效。

But, messy or not, our example did accomplish:

但是,无论是否混乱,我们的示例确实实现了:

  • Putting a process into the background.

    将流程置于后台。
  • Restoring the process to a running state in the background.

    在后台将进程恢复到运行状态。
  • Returning the process to the foreground.

    将过程返回到前台。
  • Terminating the process.

    终止过程。

When you use Ctrl+C and Ctrl+Z , you are sending signals to the process. These are shorthand ways of using the kill command. There are 64 different signals that kill can send. Use kill -l at the command line to list them. kill isn’t the only source of these signals. Some of them are raised automatically by other processes within the system

当您使用Ctrl+CCtrl+Z ,您正在向该进程发送信号。 这些是使用kill命令的简便方法kill可以发送64种不同的信号 。 在命令行上使用kill -l列出它们。 kill不是这些信号的唯一来源。 其中一些是由系统内的其他进程自动引发的

Here are some of the commonly used ones.

这是一些常用的。

  • SIGHUP: Signal 1. Automatically sent to a process when the terminal it is running in is closed.

    SIGHUP :信号1.当运行中的终端关闭时,自动发送到进程。

  • SIGINT: Signal 2. Sent to a process you hit Ctrl+C. The process is interrupted and told to terminate.

    SIGINT :信号2。发送给您按下Ctrl+C的进程。 该过程被中断并要求终止。

  • SIGQUIT: Signal 3. Sent to a process if the user sends a quit signal Ctrl+D.

    SIGQUIT :信号3。如果用户发送退出信号Ctrl+D则发送到进程。

  • SIGKILL: Signal 9. The process is immediately killed and will not attempt to close down cleanly. The process does not go down gracefully.

    SIGKILL :信号9。该进程将立即终止,并且不会尝试完全关闭。 该过程不会正常进行。

  • SIGTERM: Signal 15. This is the default signal sent by kill. It is the standard program termination signal.

    SIGTERM:信号15.这是通过发送默认的信号kill 。 它是标准程序终止信号。

  • SIGTSTP: Signal 20. Sent to a process when you use Ctrl+Z. It stops the process and puts it in the background.

    SIGTSTP :信号20。使用Ctrl+Z时发送到进程。 它将停止该过程并将其置于后台。

We must use the kill command to issue signals that do not have key combinations assigned to them.

我们必须使用kill命令来发出没有​​分配按键组合的信号。

进一步的工作控制 (Further Job Control)

A process moved into the background by using Ctrl+Z is placed in the stopped state. We have to use the bg command to start it running again. To launch a program as a running background process is simple. Append an ampersand & to the end of the command line.

使用Ctrl+Z移到后台的进程处于停止状态。 我们必须使用bg命令重新启动它。 将程序作为正在运行的后台进程启动很简单。 附加一个与符号&到命令行的末尾。

Although it is best that background processes do not write to the terminal window, we’re going to use examples that do. We need to have something in the screenshots that we can refer to. This command will start an endless loop as a background process:

尽管最好不要将后台进程写入终端窗口,但是我们将使用可以执行此操作的示例。 我们需要在屏幕快照中包含一些可以参考的内容。 此命令将启动一个无限循环作为后台进程:

while true; do echo “How-To Geek Loop Process”; sleep 3; done &

虽然是真的 做呼应“ How-To Geek Loop Process”; 睡3; 完成&

while true; do echo "How-To Geek Loop Process"; sleep 3; done & in a terminal window

We are told the job number and process ID id of the process. Our job number is 1, and the process id is 1979.  We can use these identifiers to control the process.

我们被告知流程的作业编号和流程ID。 我们的工作号为1,进程ID为1979。我们可以使用这些标识符来控制进程。

The output from our endless loop starts to appear in the terminal window. As before, we can use the command line but any commands we issue are interspersed with the output from the loop process.

无穷循环的输出开始出现在终端窗口中。 和以前一样,我们可以使用命令行,但是我们发出的所有命令都将插入到循环过程的输出中。

ls

ls

output of the background loop process interspersed with output from other commands

To stop our process we can use jobs to remind ourselves what the job number is, and then use kill.

要停止我们的流程,我们可以使用jobs提醒自己作业号是什么,然后使用kill

jobs reports that our process is job number 1. To use that number with kill we must precede it with a percent sign %.

jobs报告我们的流程是作业编号1。要将该编号与kill配合使用,必须在其前面加一个百分号%

jobs
kill %1
jobs and kill %1 in a terminal window

kill sends the SIGTERM signal, signal number 15, to the process and it is terminated. When the Enter key is next pressed, a status of the job is shown. It lists the process as “terminated.” If the process does not respond to the kill command you can take it up a notch. Use kill with SIGKILL , signal number 9. Just put the number 9 between the kill command the job number.

killSIGTERM信号(信号编号15)发送到进程,并终止进程。 再次按下Enter键时,将显示作业的状态。 它列出了该过程为“已终止”。 如果该进程未响应kill命令,则可以将其取消。 将killSIGKILL一起使用,信号号9。只需将数字9置于kill命令的作业号之间。

kill 9 %1

我们涵盖的内容 (Things We’ve Covered)

  • Ctrl+C: Sends SIGINT, signal 2, to the process—if it is accepting input—and tells it to terminate.

    Ctrl + C :将SIGINT信号2发送到该进程(如果正在接受输入),并告诉其终止。

  • Ctrl+D: Sends SISQUIT, signal 3, to the process—if it is accepting input—and tells it to quit.

    Ctrl + D :将SISQUIT (信号3)发送到该进程(如果正在接受输入),并告诉其退出。

  • Ctrl+Z: Sends SIGSTP, signal 20, to the process and tells it to stop (suspend) and become a background process.

    Ctrl + Z :将SIGSTP信号20发送到该进程,并告诉它停止(挂起)并成为后台进程。

  • jobs: Lists the background jobs and shows their job number.

    jobs :列出后台作业并显示其作业编号。

  • bg job_number: Restarts a background process. If you don’t provide a job number the last process that was turned into a background task is used.

    bg job_number :重新启动后台进程。 如果您不提供工作编号,则使用最后一个变成后台任务的过程。

  • fg job_number: brings a background process into the foreground and restarts it. If you don’t provide a job number the last process that was turned into a background task is used.

    fg job_number :使后台进程进入前台并重新启动它。 如果您不提供工作编号,则使用最后一个变成后台任务的过程。

  • commandline &: Adding an ampersand & to the end of a command line executes that command as a background task, that is running.

    命令行 添加一个与符号&于该命令作为后台任务,运行一个命令行执行的结束。

  • kill %job_number: Sends SIGTERM, signal 15, to the process to terminate it.

    kill% job_number :将SIGTERM信号15发送到进程以终止它。

  • kill 9 %job_number: Sends SIGKILL, signal 9, to the process and terminates it abruptly.

    kill 9 job_number :将SIGKILL信号9发送到该进程并突然终止。

翻译自: https://www.howtogeek.com/440848/how-to-run-and-control-background-processes-on-linux/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值