[转载][整理]解决SSH退出登陆后保持进程继续在后台运行

2017-03-21  本文已影响0人  ukeyim

zjking的几个思考写的很好啊忍不住想记下来,侵删

问题描述:

远程ssh用tar打包一个文件夹或者unrar解压一个大文件,即使加了&,退出ssh登录时解压进程中断。

ps:直接exit的话会提示zsh: you have running jobs.,强行退出会有zsh: warning: 1 jobs SIGHUPed提示。

关于SIGNUP信号

直接转一段wiki

If the process receiving SIGHUP is a Unix shell, then as part of job control it will often intercept the signal and ensure that all stopped processes are continued before sending the signal to child processes (more precisely, process groups, represented internally by the shell as a "job"), which by default terminates them.

This can be circumvented in two ways. Firstly, the Single UNIX Specification describes a shell utility called nohup, which can be used as a wrapper to start a program and make it ignore SIGHUP by default. Secondly, child process groups can be "disowned" by invoking disown with the job id, which removes the process group from the shell's job table (so they will not be sent SIGHUP), or (optionally) keeps them in the job table but prevents them from receiving SIGHUP on shell termination.

解决方法:

目前有以下几种解决方案:

  1. nohup。使用nohup命令让程序在关闭窗口(切换SSH连接)的时候程序还能继续在后台运行。
  2. disown。注意要在后台运行,<C-z>挂在后台的话会提示disown: warning: job is suspended, use 'kill -CONT -pid' to resume'
  3. 使用tmux的detach(<C-b> + D)来detach一个session,之后回去的时候tmux attach回到那个session
  4. screen。不过有tmux就别用screen了,byobu大概更好用一点但是习惯tmux了而且也不太喜欢F1,F2之类的快捷键

nohup命令说明:

用途:不挂断地运行命令。

语法:nohup Command [ Arg ... ] [ & ]

描述:nohup 命令运行由 Command 参数和任何相关的 Arg 参数指定的命令,忽略所有挂断(SIGHUP)信号。在注销后使用 nohup 命令运行后台中的程序。要运行后台中的 nohup 命令,添加 & ( 表示“and”的符号)到命令的尾部。

无论是否将 nohup 命令的输出重定向到终端,输出都将附加到当前目录的 nohup.out 文件中。如果当前目录的 nohup.out 文件不可写,输出重定向到 $HOME/nohup.out 文件中。如果没有文件能创建或打开以用于追加,那么 Command 参数指定的命令不可调用。如果标准错误是一个终端,那么把指定的命令写给标准错误的所有输出作为标准输出重定向到相同的文件描述符。

退出状态:该命令返回下列出口值:

否则,nohup 命令的退出状态是 Command 参数指定命令的退出状态。

nohup命令及其输出文件

nohup命令:如果你正在运行一个进程,而且你觉得在退出帐户时该进程还不会结束,那么可以使用nohup命令。该命令可以在你退出帐户/关闭终端之后继续运行相应的进程。nohup就是不挂起的意思( no hang up)。

该命令的一般形式为:nohup command &

如果使用nohup命令提交作业,那么在缺省情况下该作业的所有输出都被重定向到一个名为nohup.out的文件中,除非另外指定了输出文件:(也就是说自定义输出的文件名)

nohup command > myout.file 2>&1 &

在上面的例子中,输出被重定向到myout.file文件中。

结合重定向知识:
为了不让一些执行信息输出到前台(控制台),我们还会加上刚才提到的>/dev/null 2>&1命令来丢弃所有的输出:

# nohup java -jar xxxx.jar >/dev/null 2>&1 &

思考

上一篇下一篇

猜你喜欢

热点阅读