前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【Linux】《how linux work》第二章 基本命令和目录层次结构(2)

【Linux】《how linux work》第二章 基本命令和目录层次结构(2)

原创
作者头像
阿东
发布2024-04-27 10:53:32
880
发布2024-04-27 10:53:32
举报
文章被收录于专栏:《How Linux Work》《How Linux Work》

2.12 Text Editors(文本编辑器)

Speaking of editing, it’s time to learn an editor. To get serious with Unix, you must be able to edit text files without damaging them. Most parts of the system use plaintext configuration files (like the ones in /etc). It’s not difficult to edit files, but you will do it so often that you need a powerful tool for the job.

说到编辑,现在是时候学习一个编辑器了。

要认真对待Unix,你必须能够在不损坏文件的情况下编辑文本文件。

系统的大部分部分使用纯文本配置文件(比如在/etc目录下的文件)。

编辑文件并不困难,但你会经常这样做,所以需要一个强大的工具来完成这项工作。

You should try to learn one of the two de facto standard Unix text editors, vi and Emacs. Most Unix wizards are religious about their choice of editor, but don’t listen to them. Just choose for yourself. If you choose one that matches the way that you work, you’ll find it easier to learn. Basically, the choice comes down to this:

你应该尝试学习两个事实上的标准Unix文本编辑器之一,vi和Emacs。

大多数Unix专家对于他们选择的编辑器都有宗教般的热爱,但不要听他们的。

只需选择适合自己工作方式的编辑器即可,这样你会发现学习起来更容易。

基本上,选择编辑器有以下几点:

o If you want an editor that can do almost anything and has extensive online help, and you don’t mind doing ome extra typing to get these features, try Emacs. o If speed is everything, give vi a shot; it “plays” a bit like a video game.

  • 如果你想要一个几乎可以做任何事情并且有广泛在线帮助的编辑器,而且不介意为了使用这些功能而多输入一些命令,可以尝试Emacs。
  • 如果速度至关重要,可以试试vi;它的使用方式有点像玩电子游戏。

Learning the vi and Vim Editors: Unix Text Processing, 7th edition (O’Reilly, 2008) can tell you everything you need to know about vi. For Emacs, use the online tutorial: Start Emacs, press CTRL-H, and then type T. Or read GNU Emacs Manual (Free Software Foundation, 2011).

《学习vi和Vim编辑器:Unix文本处理,第7版》(O'Reilly,2008)可以告诉你关于vi的一切。

对于Emacs,可以使用在线教程:启动Emacs,按下CTRL-H,然后输入T。

或者阅读《GNU Emacs手册》(自由软件基金会,2011)。

You might be tempted to experiment with a friendlier editor when you first start out, such as Pico or one of the myriad GUI editors out there, but if you tend to make a habit out of the first thing that you use, you don’t want to go down this route.

当你刚开始时,可能会尝试使用一个更友好的编辑器,比如Pico或者其他各种图形界面编辑器,但如果你倾向于养成第一次使用的习惯,就不要走这条路。

NOTE Editing text is where you’ll first start to see a difference between the terminal and the GUI. Editors such as vi run inside the terminal window, using the standard terminal I/O interface. GUI editors start their own window and present their own interface, independent of terminals. Emacs runs in a GUI by default but will run in a terminal window as well. 注意 编辑文本是你首次开始看到终端和图形界面之间差异的地方。 例如vi这样的编辑器在终端窗口内运行,使用标准终端I/O接口。 图形界面编辑器则启动自己的窗口,并呈现独立于终端的界面。 Emacs默认在图形界面中运行,但也可以在终端窗口中运行。

2.13 Getting Online Help(获取在线帮助)

Linux systems come with a wealth of documentation. For basic commands, the manual pages (or man pages) will tell you what you need to know. For example, to see the manual page for the ls command, run man as follows:

Linux系统提供了丰富的文档资源。对于基本命令,手册页(或man页)会告诉您所需的信息。

例如,要查看ls命令的手册页,请运行以下命令:

代码语言:javascript
复制
$ man ls

Most manual pages concentrate primarily on reference information, perhaps with some examples and crossreferences, but that’s about it. Don’t expect a tutorial, and don’t expect an engaging literary style

大多数手册页主要集中在参考信息上,可能会包含一些示例和交叉引用,但仅此而已。

不要期望有教程,也不要期望有引人入胜的文学风格。

When programs have many options, the manual page often lists the options in some systematic way (for example, in alphabetical order), but it won’t tell you what the important ones are. If you’re patient, you can usually find what you need to know in the man page. If you’re impatient, ask a friend—or pay someone to be your friend so that you can ask him or her.

当程序有许多选项时,手册页通常会以某种系统的方式列出这些选项(例如按字母顺序),但它不会告诉您哪些是重要的选项。

如果您耐心一点,通常可以在手册页中找到所需的信息。

如果您不耐烦,可以向朋友询问,或者付钱请人充当您的朋友,这样您就可以向他们提问。

To search for a manual page by keyword, use the -k option:

要按关键字搜索手册页,请使用-k选项:

代码语言:javascript
复制
$ man -k keyword

This is helpful if you don’t quite know the name of the command that you want. For example, if you’re looking for a command to sort something, run:

如果您不太知道所需命令的名称,这将很有帮助。例如,如果您正在寻找一个用于排序的命令,请运行:

代码语言:javascript
复制
$ man -k sort
--snip--
comm (1) - compare two sorted files line by line
qsort (3) - sorts an array
sort (1) - sort lines of text files
sortm (1) - sort messages
tsort (1) - perform topological sort
--snip--

The output includes the manual page name, the manual section (see below), and a quick description of what the manual page contains.

输出结果包括手册页面名称、手册部分(见下文)以及手册页面内容的快速描述。

NOTE If you have any questions about the commands described in the previous sections, you may be able to find the answers by using the man command. 注意 如果您对前面章节中描述的命令有任何疑问,可以使用 man 命令找到答案。

Manual pages are referenced by numbered sections. When someone refers to a manual page, the section number appears in parentheses next to the name, like ping(8), for example. Table 2-3 lists the sections and their numbers.

手册页面按章节编号引用。当有人引用手册页面时,章节编号会出现在名称旁边的括号中,例如 ping(8)。表 2-3 列出了章节及其编号。

Table 2-3. Online Manual Sections

表 2-3. 联机手册章节

Table 2-3. Online Manual Sections

Sections 1, 5, 7, and 8 should be good supplements to this book. Section 4 may be of marginal use, and Section 6 would be great if only it were a little larger. You probably won’t be able to use Section 3 if you aren’t a programmer, but you may be able to understand some of the material in Section 2 once you’ve read more about system calls in this book.

第1、5、7和8节应该是这本书的很好的补充。第4节可能有一些边缘用途,如果第6节能再大一点就更好了。

如果你不是程序员,可能无法使用第3节,但是在阅读本书关于系统调用的更多内容后,你可能能够理解第2节的一些材料。

You can select a manual page by section, which is sometimes important because man displays the first manual page that it finds when matching a particular search term. For example, to read the /etc/passwd file description (as opposed to the passwd command), you can insert the section number before the page name:

您可以按节选择手册页,这有时很重要,因为当匹配特定搜索词时,man会显示它找到的第一个手册页。

例如,要阅读/etc/passwd文件的描述(而不是passwd命令),您可以在页面名称之前插入节号:

代码语言:javascript
复制
$ man 5 passwd

Manual pages cover the essentials, but there are many more ways to get online help. If you’re just looking for a certain option for a command, try entering a command name followed by --help or -h (the option varies from command to command). You may get a deluge (as in the case of ls --help), or you may find just what you’re looking for

手册页涵盖了基本内容,但还有许多其他获取在线帮助的方法。

如果您只是想要某个命令的特定选项,请尝试输入命令名称后跟--help或-h(选项因命令而异)。

您可能会得到一大堆信息(例如ls --help的情况),或者您可能只找到您需要的内容。

Some time ago, the GNU Project decided that it didn’t like manual pages very much and switched to another format called info (or texinfo). Often this documentation goes further than a typical manual page does, but it is sometimes more complex. To access an info manual, use info with the command name:

一段时间以前,GNU项目决定不太喜欢手册页,而是转向另一种称为info(或texinfo)的格式。

通常,这种文档比典型的手册页更详细,但有时更复杂。

要访问info手册,请使用info和命令名称:

代码语言:javascript
复制
$ info command

Some packages dump their available documentation into /usr/share/doc with no regard for online manual systems such as man or info. See this directory on your system if you find yourself searching for documentation. And of course, search the Internet.

一些软件包会将其可用的文档转储到/usr/share/doc中,而不考虑man或info等在线手册系统。

如果您发现自己在搜索文档,请查看您系统上的此目录。

当然,还可以在互联网上搜索。

2.14 Shell Input and Output( Shell 输入和输出)

Now that you’re familiar with basic Unix commands, files, and directories, you’re ready to learn how to redirect standard input and output. Let’s start with standard output.

现在你已经熟悉了基本的Unix命令、文件和目录,你可以学习如何重定向标准输入和输出了。我们先从标准输出开始。

To send the output of command to a file instead of the terminal, use the > redirection character:

要将命令的输出发送到文件而不是终端,请使用重定向字符 >:

代码语言:javascript
复制
$ command > file

The shell creates file if it does not already exist. If file exists, the shell erases (clobbers) the original file first. (Some shells have parameters that prevent clobbering. For example, enter set -C to avoid clobbering in bash.)

如果文件不存在,shell会创建该文件。

如果文件已经存在,shell会先擦除(覆盖)原文件。(一些shell有参数可以防止擦除。

例如,在bash中输入set -C可以避免擦除。)

你也可以使用 >> 重定向语法将输出追加到文件中而不是覆盖它:

代码语言:javascript
复制
$ command >> file

This is a handy way to collect output in one place when executing sequences of related commands.

这是在执行相关命令序列时,将输出收集到一个地方的便捷方式。

To send the standard output of a command to the standard input of another command, use the pipe character (|). To see how this works, try these two commands:

要将一个命令的标准输出发送到另一个命令的标准输入,使用管道符号 |。

试试下面这两个命令,看看它们是如何工作的:

代码语言:javascript
复制
$ head /proc/cpuinfo
$ head /proc/cpuinfo | tr a-z A-Z

You can send output through as many piped commands as you wish; just add another pipe before each additional command.

你可以通过任意多个管道命令发送输出,只需在每个附加命令之前添加另一个管道符号。

2.14.1 Standard Error(标准错误)

Occasionally, you may redirect standard output but find that the program still prints something to the terminal. This is called standard error (stderr); it’s an additional output stream for diagnostics and debugging.

有时,你可能重定向了标准输出,但发现程序仍然在终端打印一些内容。

这被称为标准错误(stderr),它是用于诊断和调试的额外输出流。

For example, this command produces an error:

例如,下面的命令会产生一个错误:

代码语言:javascript
复制
$ ls /fffffffff > f

After completion, f should be empty, but you still see the following error message on the terminal as standard error:

完成后,f应该是空的,但你仍然会在终端上看到以下标准错误的错误消息:

代码语言:javascript
复制
ls: cannot access /fffffffff: No such file or directory

You can redirect the standard error if you like. For example, to send standard output to f and standard error to e, use the 2> syntax, like this:

你可以重定向标准错误。例如,要将标准输出发送到f,将标准错误发送到e,可以使用 2> 语法,像这样:

代码语言:javascript
复制
$ ls /fffffffff > f 2> e

The number 2 specifies the stream ID that the shell modifies. Stream ID 1 is standard output (the default), and 2 is standard error.

数字2指定了shell修改的流ID。流ID 1是标准输出(默认值),2是标准错误。

You can also send the standard error to the same place as stdout with the >& notation. For example, to send both standard output and standard error to the file named f, try this command:

你也可以使用 >& 符号将标准错误发送到与stdout相同的位置。例如,要将标准输出和标准错误都发送到名为f的文件中,可以尝试以下命令:

代码语言:javascript
复制
$ ls /fffffffff > f 2>&1

2.14.2 Standard Input Redirection(标准输入重定向)

To channel a file to a program’s standard input, use the < operator:

要将文件传递给程序的标准输入,请使用 < 运算符:

代码语言:javascript
复制
$ head < /proc/cpuinfo

You will occasionally run into a program that requires this type of redirection, but because most Unix commands accept filenames as arguments, this isn’t very common. For example, the preceding command could have been written as head /proc/cpuinfo.

偶尔会遇到需要这种类型重定向的程序,但因为大多数Unix命令接受文件名作为参数,所以这种情况并不常见。

例如,前面的命令也可以写成 head /proc/cpuinfo。

2.15 Understanding Error Messages(理解错误消息)

When you encounter a problem on a Unix-like system such as Linux, you must read the error message. Unlike messages from other operating systems, Unix errors usually tell you exactly what went wrong.

在类Unix系统(如Linux)上遇到问题时,必须阅读错误消息。与其他操作系统的消息不同,Unix的错误消息通常会准确告诉你出了什么问题。

2.15.1 UNIX错误消息的组成

Most Unix programs generate and report the same basic error messages, but there can be subtle differences between the output of any two programs. Here’s an example that you’ll certainly encounter in some form or other:

大多数Unix程序生成并报告相同的基本错误消息,但两个程序的输出之间可能存在细微差别。以下是一个你肯定会以某种形式遇到的示例:

代码语言:javascript
复制
$ ls /dsafsda 
ls: cannot access /dsafsda: No such file or directory 

There are three components to this message:

这个消息包含三个组成部分:

o The program name, ls. Some programs omit this identifying information, which can be annoying when writing shell scripts, but it’s not really a big deal. o The filename, /dsafsda, which is a more specific piece of information. There’s a problem with this path. o The error No such file or directory indicates the problem with the filename.

o 程序名称 ls。一些程序会省略这个标识信息,在编写shell脚本时可能会有些烦人,但这并不是什么大问题。 o 文件名 /dsafsda,它是一个更具体的信息。这个路径有问题。 o 错误消息 "没有那个文件或目录" 指示了文件名的问题。

Putting it all together, you get something like “ls tried to open /dsafsda but couldn’t because it doesn’t exist.” This may seem obvious, but these messages can get a little confusing when you run a shell script that includes an erroneous command under a different name.

综合起来,你会得到类似于 "ls试图打开/dsafsda,但由于它不存在,所以无法打开" 的信息。这似乎很明显,但当你在以不同的名称运行一个包含错误命令的shell脚本时,这些消息可能会有点令人困惑。

When troubleshooting errors, always address the first error first. Some programs report that they can’t do anything before reporting a host of other problems. For example, say you run a fictitious program called scumd and you see this error message:

在排除错误时,始终首先处理第一个错误。有些程序在报告一系列其他问题之前可能会报告无法执行任何操作的错误。例如,假设你运行一个名为scumd的虚构程序,并看到以下错误消息:

代码语言:javascript
复制
scumd: cannot access /etc/scumd/config: No such file or directory

Following this is a huge list of other error messages that looks like a complete catastrophe. Don’t let those other errors distract you. You probably just need to create /etc/scumd/config.

接下来是一个巨大的错误消息列表,看起来像是一场完全的灾难。不要让这些其他错误分散你的注意力。你可能只需要创建/etc/scumd/config。

NOTE Don’t confuse error messages with warning messages. Warnings often look like errors, but they contain the word warning. A warning usually means something is wrong but the program will try to continue running anyway. To fix a problem noted in a warning message, you may have to hunt down a process and kill it before doing anything else. (You’ll learn about listing and killing processes in 2.16 Listing and Manipulating Processes.) 注意: 不要将错误消息与警告消息混淆。警告通常看起来像错误,但它们包含了"警告"一词。 警告通常意味着有些问题,但程序将尝试继续运行。 要修复警告消息中指出的问题,你可能需要在执行其他操作之前查找并终止一个进程(你将在2.16 列出和操作进程中学习如何列出和终止进程)。

2.15.2 Common Errors(常见错误)

Many errors that you’ll encounter in Unix programs result from things that can go wrong with files and processes. Here’s an error message hit parade:

在Unix程序中,许多错误是由于文件和进程出现问题导致的。以下是一些常见的错误信息:

No such file or directory(没有这个文件或目录)

This is the number one error. You tried to access a file that doesn’t exist. Because the Unix file I/O system doesn’t discriminate between files and directories, this error message occurs everywhere. You get it when you try to read a file that does not exist, when you try to change to a directory that isn’t there, when you try to write to a file in a directory that doesn’t exist, and so on.

这是最常见的错误。您尝试访问一个不存在的文件。因为Unix文件I/O系统对文件和目录没有区别,所以这个错误信息无处不在。当您尝试读取一个不存在的文件、切换到一个不存在的目录、向一个不存在的目录中的文件写入时,都会出现这个错误信息。

File exists(文件已存在)

In this case, you probably tried to create a file that already exists. This is common when you try to create a directory with the same name as a file.

在这种情况下,您可能尝试创建一个已经存在的文件。当您尝试以与文件同名的方式创建一个目录时,这种情况很常见。

Not a directory, Is a directory 不是一个目录,是一个目录

These messages pop up when you try to use a file as a directory or a directory as a file. For example:

当您尝试将文件用作目录或将目录用作文件时,这些消息会弹出。例如:

代码语言:javascript
复制
$ touch a 
$ touch a/b 
touch: a/b: Not a directory 

Notice that the error message only applies to the a part of a/b. When you encounter this problem, you may need to dig around a little to find the path component that is being treated like a directory.

请注意,错误消息仅适用于a/b中的a部分。当遇到此问题时,您可能需要仔细查找被视为目录的路径组件。

No space left on device 设备上没有剩余空间

You’re out of disk space.

您的磁盘空间已用完。

Permission denied(权限被拒绝)

You get this error when you attempt to read or write to a file or directory that you’re not allowed to access (you have insufficient privileges). This error also shows when you try to execute a file that does not have the execute bit set (even if you can read the file). You’ll read more about permissions in 2.17 File Modes and Permissions.

当您尝试读取或写入一个您没有权限访问的文件或目录时,会出现此错误(权限不足)。当您尝试执行一个没有设置执行位的文件时(即使您可以读取该文件),也会显示此错误。您将在2.17文件模式和权限中了解更多关于权限的内容。

Operation not permitted(操作不允许)

This usually happens when you try to kill a process that you don’t own.

通常在您尝试终止一个您不拥有的进程时会发生这种情况

Segmentation fault, Bus error( 分段错误,总线错误)

A segmentation fault essentially means that the person who wrote the program that you just ran screwed up somewhere. The program tried to access a part of memory that it was not allowed to touch, and the operating system killed it. Similarly, a bus error means that the program tried to access some memory in a particular way that it shouldn’t. When you get one of these errors, you might be giving a program some input that it did not expect.

分段错误基本上意味着刚刚运行的程序的编写者出现了错误。

该程序试图访问不允许访问的内存部分,导致操作系统将其终止。

类似地,总线错误意味着程序试图以某种不应该的方式访问某个内存。

当您遇到这些错误时,可能是给程序输入了它不期望的内容。

2.16 Listing and Manipulating Processes(进程的列举和操作)

Recall from Chapter 1 that a process is a running program. Each process on the system has a numeric process ID (PID). For a quick listing of running processes, just run ps on the command line. You should get a list like this one:

回顾一下第一章,进程是正在运行的程序。系统上的每个进程都有一个数字进程ID(PID)。要快速列出正在运行的进程,只需在命令行上运行ps命令。您应该会得到一个类似下面的列表:

代码语言:javascript
复制
$ ps
 PID TTY STAT TIME COMMAND
 520 p0 S 0:00 -bash
 545 ? S 3:59 /usr/X11R6/bin/ctwm -W
 548 ? S 0:10 xclock -geometry -0-0
2159 pd SW 0:00 /usr/bin/vi lib/addresses
31956 p3 R 0:00 ps

The fields are as follows:

o PID. The process ID. o TTY. The terminal device where the process is running. More about this later. o STAT. The process status, that is, what the process is doing and where its memory resides. For example, S means sleeping and R means running. (See the ps(1) manual page for a description of all the symbols.) o TIME. The amount of CPU time in minutes and seconds that the process has used so far. In other words, the total amount of time that the process has spent running instructions on the processor. o COMMAND. This one might seem obvious, but be aware that a process can change this field from its original value.

字段的含义如下: o PID:进程ID。 o TTY:进程运行的终端设备。关于此后面会有更多介绍。 o STAT:进程的状态,即进程正在做什么以及其内存所在的位置。例如,S表示睡眠,R表示运行。(有关所有符号的描述,请参阅ps(1)手册页。) o TIME:进程到目前为止使用的CPU时间(以分钟和秒为单位)。换句话说,进程在处理器上运行指令所花费的总时间。 o COMMAND:这个可能看起来很明显,但请注意,进程可以将此字段从其原始值更改为其他值。

2.16.1 命令选项

The ps command has many options. To make things more confusing, you can specify options in three different styles—Unix, BSD, and GNU. Many people find the BSD style to be the most comfortable (perhaps because it involves less typing), so we’ll use the BSD style in this book. Here are some of the most useful option combinations:

ps命令有许多选项。为了使事情更加混乱,你可以以三种不同的风格指定选项——Unix、BSD和GNU。

许多人发现BSD风格最舒适(也许是因为它需要更少的打字),所以在本书中我们将使用BSD风格。以下是一些最有用的选项组合:

image.png

As with other programs, you can combine options, as in ps aux and ps auxw. To check on a specific process, add its PID to the argument list of the ps command. For example, to inspect the current shell process, you could use ps

, because

is a shell variable that evaluates to the current shell’s PID. (You’ll find information on the administration commands top and lsof in Chapter 8. These can be useful for locating processes, even when doing something other than system maintenance.)

与其他程序一样,您可以组合选项,例如 ps aux 和 ps auxw。

要检查特定进程,请将其 PID 添加到 ps 命令的参数列表中。

例如,要检查当前 shell 进程,可以使用 ps u

,因为

是一个 shell 变量,它的值为当前 shell 的 PID。

(关于管理命令 top 和 lsof 的信息可以在第8章找到。即使在进行系统维护以外的操作时,它们也可以用于定位进程。)

2.16.2 Killing Processes(终止进程)

To terminate a process, send it a signal with the kill command. A signal is a message to a process from the kernel. When you run kill, you’re asking the kernel to send a signal to another process. In most cases, all you need to do is this:

要终止一个进程,请使用 kill 命令向其发送一个信号。信号是内核向进程发送的一条消息。

当您运行 kill 命令时,您正在请求内核向另一个进程发送一个信号。

在大多数情况下,您只需要执行以下操作:

代码语言:javascript
复制
$ kill pid

There are many types of signals. The default is TERM, or terminate. You can send different signals by adding an extra option to kill. For example, to freeze a process instead of terminating it, use the STOP signal:

有许多类型的信号。默认信号是 TERM,即终止。您可以通过在 kill 命令中添加额外选项来发送不同的信号。例如,要冻结一个进程而不是终止它,请使用 STOP 信号:

代码语言:javascript
复制
$ kill -STOP pid

A stopped process is still in memory, ready to pick up where it left off. Use the CONT signal to continue running the process again:

一个被停止的进程仍然在内存中,准备继续从上次停止的地方继续执行。使用 CONT 信号可以继续运行该进程:

代码语言:javascript
复制
$ kill -CONT pid

NOTE Using ctrl-c to terminate a process that is running in the current terminal is the same as using kill to end the process with the INT (interrupt) signal. 注意 在当前终端中使用ctrl-c终止正在运行的进程与使用kill命令以INT(中断)信号结束进程是相同的。

The most brutal way to terminate a process is with the KILL signal. Other signals give the process a chance to clean up after itself, but KILL does not. The operating system terminates the process and forcibly removes it from memory. Use this as a last resort.

终止进程最残忍的方式是使用KILL信号。其他信号给予进程一个机会自我清理,但KILL不会。

操作系统终止进程并强制从内存中移除它。

请将其视为最后的手段。

You should not kill processes indiscriminately, especially if you don’t know what they’re doing. You may be shooting yourself in the foot.

您不应该随意终止进程,特别是当您不知道它们在做什么时。您可能会自食其果。

You may see other users entering numbers instead of names with kill; for example, kill -9 instead of kill -KILL. This is because the kernel uses numbers to denote the different signals; you can use kill this way if you know the number of the signal that you want to send.

您可能会看到其他用户使用数字而不是名称输入kill命令;例如,kill -9而不是kill -KILL。

这是因为内核使用数字来表示不同的信号;如果您知道要发送的信号的编号,可以使用这种方式。

2.16.3 Job Control(作业控制)

Shells also support job control, which is a way to send TSTP (similar to STOP) and CONT signals to programs by using various keystrokes and commands. For example, you can send a TSTP signal with CTRL-Z, then start the process again by entering fg (bring to foreground) or bg (move to background; see the next section). But despite its utility and the habits of many experienced users, job control is not necessary and can be confusing for beginners: It’s common for users to press CTRL-Z instead of CTRL-c, forget about what they were running, and eventually end up with numerous suspended processes hanging around.

Shell 还支持作业控制,这是一种通过使用各种按键和命令向程序发送 TSTP(类似于 STOP)和 CONT 信号的方式。

例如,你可以使用 CTRL-Z 发送 TSTP 信号,然后通过输入 fg(将进程带到前台)或 bg(移到后台;请参见下一节)来重新启动进程。

但是,尽管它很实用并且许多有经验的用户习惯使用它,但作业控制对于初学者来说并不是必需的,可能会造成困惑:用户经常按下 CTRL-Z 而不是 CTRL-C,忘记他们正在运行什么,最终导致大量挂起的进程存在。

HINT To see if you’ve accidentally suspended any processes on your current terminal, run the jobs command. 提示 要查看是否在当前终端上意外挂起了任何进程,请运行 jobs 命令。

If you want to run multiple shells, run each program in a separate terminal window, put noninteractive processes in the background (as explained in the next section), or learn to use the screen program.

如果你想运行多个 shell,请在单独的终端窗口中运行每个程序,将非交互式进程放在后台(如下一节所述),或学习使用 screen 程序。

2.16.4 Background Processes(后台进程)

Normally, when you run a Unix command from the shell, you don’t get the shell prompt back until the program finishes executing. However, you can detach a process from the shell and put it in the “background” with the ampersand (&); this gives you the prompt back. For example, if you have a large file that you need to decompress with gunzip (you’ll see this in 2.18 Archiving and Compressing Files), and you want to do some other stuff while it’s running, run a command like this one:

通常,当你从 shell 运行 Unix 命令时,直到程序执行完成,你才会得到 shell 提示符。

然而,你可以使用和号(&)将一个进程从 shell 中分离并放到“后台”;这样你就能够立即得到提示符。

例如,如果你有一个需要使用 gunzip(你将在 2.18 文件归档和压缩 中看到)解压缩的大文件,并且你希望在它运行时做其他事情,可以运行以下命令:

代码语言:javascript
复制
$ gunzip file.gz &

The shell should respond by printing the PID of the new background process, and the prompt should return immediately so that you can continue working. The process will continue to run after you log out, which comes in particularly handy if you have to run a program that does a lot of number crunching for a while. (Depending on your setup, the shell might notify you when the process completes.)

Shell 应该会打印新后台进程的 PID,并立即返回提示符,以便你可以继续工作。

该进程将在你退出登录后继续运行,这在你需要运行一个进行大量数值计算的程序时特别方便。

(根据你的设置,当进程完成时,shell 可能会通知你。)

The dark side of running background processes is that they may expect to work with the standard input (or worse, read directly from the terminal). If a program tries to read something from the standard input when it’s in the background, it can freeze (try fg to bring it back) or terminate. Also, if the program writes to the standard output or standard error, the output can appear in the terminal window with no regard for anything else running there, meaning that you can get unexpected output when you’re working on something else.

运行后台进程的不好之处在于它们可能希望与标准输入一起工作(或更糟糕的是,直接从终端读取)。

如果一个程序在后台时尝试从标准输入读取内容,它可能会冻结(尝试使用 fg 将其带回前台)或终止。

此外,如果程序写入标准输出或标准错误,输出可能会出现在终端窗口中,而不考虑其他正在运行的内容,这意味着在你处理其他事情时可能会得到意外的输出。

The best way to make sure that a background process doesn’t bother you is to redirect its output (and possibly input) as described in 2.14 Shell Input and Output.

确保后台进程不会打扰你的最佳方法是根据 2.14 Shell 输入和输出 中所述重定向其输出(和可能的输入)。

If spurious output from background processes gets in your way, learn how to redraw the content of your terminal window. The bash shell and most full-screen interactive programs support CTRL-L to redraw the entire screen. If a program is reading from the standard input, CTRL-R usually redraws the current line, but pressing the wrong sequence at the wrong time can leave you in an even worse situation than before. For example, entering CTRL-R at the bash prompt puts you in reverse isearch mode (press ESC to exit).

如果后台进程产生了无关紧要的输出,学习如何重新绘制终端窗口的内容。

bash shell和大多数全屏交互式程序都支持使用CTRL-L重新绘制整个屏幕。

如果一个程序正在读取标准输入,通常使用CTRL-R重新绘制当前行,但是在错误的时间按下错误的序列可能会使情况变得更糟。

例如,在bash提示符下输入CTRL-R会进入反向搜索模式(按ESC键退出)。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 2.12 Text Editors(文本编辑器)
  • 2.13 Getting Online Help(获取在线帮助)
  • 2.14 Shell Input and Output( Shell 输入和输出)
    • 2.14.1 Standard Error(标准错误)
      • 2.14.2 Standard Input Redirection(标准输入重定向)
      • 2.15 Understanding Error Messages(理解错误消息)
        • 2.15.1 UNIX错误消息的组成
          • 2.15.2 Common Errors(常见错误)
            • No such file or directory(没有这个文件或目录)
            • File exists(文件已存在)
            • Not a directory, Is a directory 不是一个目录,是一个目录
            • No space left on device 设备上没有剩余空间
            • Permission denied(权限被拒绝)
            • Operation not permitted(操作不允许)
            • Segmentation fault, Bus error( 分段错误,总线错误)
        • 2.16 Listing and Manipulating Processes(进程的列举和操作)
          • 2.16.1 命令选项
            • 2.16.2 Killing Processes(终止进程)
              • 2.16.3 Job Control(作业控制)
                • 2.16.4 Background Processes(后台进程)
                领券
                问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
                http://www.vxiaotou.com