如何将当前正在运行的 linux 进程置于后台?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13676457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 17:56:41  来源:igfitidea点击:

How can I put the current running linux process in background?

linuxbashshellbackground

提问by Mirage

I have a command that uploads files using git to a remote server from the Linux shell and it will take many hours to finish.

我有一个使用 git 将文件从 Linux shell 上传到远程服务器的命令,它需要几个小时才能完成。

How can I put that running program in background? So that I can still work on shell and that process also gets completed?

我怎样才能把那个正在运行的程序放在后台?这样我仍然可以在 shell 上工作并且该过程也完成了吗?

采纳答案by Ed Heal

Suspend the process with CTRL+Z then use the command bgto resume it in background. For example:

使用 CTRL+Z 暂停进程,然后使用该命令bg在后台恢复它。例如:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bgusage in bashmanual page:

手册页中有关作业控制和bg使用的更多信息bash

JOB CONTROL
Typing the suspendcharacter (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec...]
Resume each suspended job jobspecin the background, as if it had been started with &. If jobspecis not present, the shell's notion of the current jobis used.

作业控制在进程运行时
键入挂起字符(通常是 ^Z、Control-Z)会导致该进程停止并将控制权返回给 bash。[...] 然后用户可以操纵此作业的状态,使用 bg 命令在后台继续它,[...]。A ^Z 立即生效,并具有导致挂起输出和预先输入被丢弃的额外副作用。

bg [ jobspec...]在后台
恢复每个暂停的作业jobspec,就好像它是用 & 开始的一样。如果 jobspec不存在,则使用 shell 的当前作业概念。

EDIT

编辑

To start a process where you can even kill the terminal and it still carries on running

启动一个进程,你甚至可以杀死终端,它仍然继续运行

nohup [command] [-args] > [filename] 2>&1 &

e.g.

例如

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

要忽略输出(不是很明智),请将文件名更改为 /dev/null

To get the error message set to a different file change the &1to a filename.

要将错误消息设置为不同的文件,请将其更改&1为文件名。

In addition: You can use the jobscommand to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1or kill %2with the number being the index of the process.

此外:您可以使用该jobs命令查看这些后台进程的索引列表。您可以通过运行kill %1kill %2将数字作为进程的索引来终止后台进程。