[linux] nohup - keeps job running at backend

本文介绍如何利用nohup命令使Linux中的任务在后台持续运行,即使用户登出也不受影响。通过nohup命令启动的任务会将输出重定向到nohup.out文件,并且可以通过ps和grep组合命令来查找并使用kill命令结束该任务。
Normally we log in a Linux machine using ssh. And when we logs out, those jobs started by the shell will get killed if they're not deamon or running at backend. [b]nohup[/b] is a useful tool to keep the job running at backend to prevent this "auto killed" behavior from happening.

Here's how to use it:


# nohup myjob &


We'll see something printed out:


appending output to nohup.out


Meaning it's up. All the output info of [i]myjob[/i] will be kept in nohup.out of the current directory.

If we logout, [i]myjob[/i] will keep running at the backend.

To kill [i]myjob[/i], normally we use the command below to find out the pid, and use the [i]kill[/i] command to stop the process.


ps -A | grep myjob
### `ps -ef | grep psychological-backend.jar` 执行结果解析 `ps -ef` 用于显示系统中所有进程的详细信息,`ps` 是进程状态(process status)的缩写,`-e` 表示显示所有进程,`-f` 表示显示完整格式的输出。`grep psychological-backend.jar` 则是在 `ps -ef` 的输出结果中筛选出包含 `psychological-backend.jar` 的行。 执行该命令后,如果有输出且包含 `psychological-backend.jar` 相关信息,那么说明系统中存在运行该 JAR 文件的进程。例如,可能会出现如下输出: ```plaintext root 1234 1 0 10:00 ? 00:00:05 java -jar psychological-backend.jar ``` 这里 `1234` 是进程 ID(PID),表示 `psychological-backend.jar` 进程正在以 `root` 用户身份运行。 如果只输出了类似 `root 9964 1389 0 13:17 pts/0 00:00:00 grep --color=auto psychological-backend.jar` 这样的内容,实际上这只是 `grep` 命令自身的进程信息,意味着系统中可能并没有正在运行的 `psychological-backend.jar` 进程。 ### `退出 1` 的含义 在 Linux 系统中,命令执行结束后会返回一个退出状态码。正常情况下,命令成功执行返回状态码 `0`,而返回 `1` 通常表示命令执行过程中出现了错误或者没有找到匹配的内容。在 `ps -ef | grep psychological-backend.jar` 这个场景中,`退出 1` 可能表示 `grep` 没有在 `ps -ef` 的输出中找到包含 `psychological-backend.jar` 的行,即系统中没有运行该 JAR 文件的进程。 ### `nohup java -jar psychological-backend.jar --server.port=1208 > app.log 2>&1` 含义 - `nohup`:该命令用于在用户退出登录或者终端关闭后,让程序继续在后台运行,不受 HUP(hangup)信号的影响。 - `java -jar psychological-backend.jar`:这是启动 Java 应用程序的标准命令,通过 `java` 虚拟机执行 `psychological-backend.jar` 文件。 - `--server.port=1208`:这是传递给 `psychological-backend.jar` 应用程序的参数,指定应用程序监听的端口为 `1208`。 - `> app.log`:将标准输出(stdout)重定向到 `app.log` 文件中,即程序运行过程中的正常输出信息会被写入该文件。 - `2>&1`:将标准错误输出(stderr)重定向到标准输出,也就是将程序运行过程中的错误信息也写入到 `app.log` 文件中。 ### 示例代码 以下是一个简单的示例,展示如何结合使用这些命令: ```bash # 启动 psychological-backend.jar 应用程序并将输出重定向到 app.log 文件 nohup java -jar psychological-backend.jar --server.port=1208 > app.log 2>&1 & # 查看是否有 psychological-backend.jar 进程在运行 ps -ef | grep psychological-backend.jar ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值