Linux笔记 #05# 断开远程连接后保持程序运行

教程:Linux 技巧:让进程在后台可靠运行的几种方法

网上搜索了一下,方法很多,选用最流行的 screen

命令参考:http://man.linuxde.net/screen 

1. 安装

root@xkfx:~# apt install screen

...

root@xkfx:~# screen -list 列出所有会话
There is a screen on:
        1883.pts-0.xkfx (03/04/2018 12:06:15 PM)        (Attached)
1 Socket in /var/run/screen/S-root.

2. 基本操作

例如说我现在打算断开 ssh ,又希望XXXXXXXX程序继续运行:

root@xkfx:~# screen -ls
There is a screen on:
1883.pts-0.xkfx (03/04/2018 12:06:14 PM) (Detached)
1 Socket in /var/run/screen/S-root.

root@xkfx:~# screen -dmS MyWorker

(创建一个新的视窗,并指定名字)
root@xkfx:~# screen -ls
There are screens on:
2210.MyWorker (03/04/2018 12:38:55 PM) (Detached)
1883.pts-0.xkfx (03/04/2018 12:06:15 PM) (Detached)
2 Sockets in /var/run/screen/S-root.

root@xkfx:~# screen -r 2227.MyWorker 

(screen -r 2227 或者 screen -r MyWorker 均可)

(Attached某个视窗,也可以理解为进入某个视窗)

root@xkfx:/# screen -ls
There are screens on:
2227.MyWorker (03/04/2018 12:40:00 PM) (Attached)
1883.pts-0.xkfx (03/04/2018 12:06:15 PM) (Detached)
2 Sockets in /var/run/screen/S-root.

(执行你想进行的任何操作)

root@xkfx:/# cd /opt/antpool/cpuminer-2.5.0/
root@xkfx:/opt/antpool/cpuminer-2.5.0# ./minerd -o stratum+tcp://stratum-ltc.antpool.com:8888 -u xkfx.01
[2018-03-04 12:45:10] 1 miner threads started, using 'scrypt' algorithm.
[2018-03-04 12:45:10] Starting Stratum on stratum+tcp://stratum-ltc.antpool.com:8888
[2018-03-04 12:45:12] thread 0: 4104 hashes, 15.34 khash/s

[detached from 2227.MyWorker]

(退出某个视窗,但保持该视窗工作继续进行。这里的操作是 Ctrl + A + D)

root@xkfx:~# screen -ls
There are screens on:
2227.MyWorker (03/04/2018 12:40:00 PM) (Detached)
1883.pts-0.xkfx (03/04/2018 12:06:15 PM) (Detached)
2 Sockets in /var/run/screen/S-root.

好了,现在可以断开 ssh了。

重新连接ssh,看看程序是不是仍在运行:

root@xkfx:~# screen -ls
There are screens on:
2227.MyWorker (03/04/2018 12:39:59 PM) (Detached)
1883.pts-0.xkfx (03/04/2018 12:06:14 PM) (Detached)
2 Sockets in /var/run/screen/S-root.

root@xkfx:~# screen -r 2227.MyWorker

[2018-03-04 13:26:38] accepted: 28/28 (100.00%), 15.55 khash/s (yay!!!)
[2018-03-04 13:27:38] thread 0: 932832 hashes, 15.55 khash/s
[2018-03-04 13:27:39] thread 0: 9480 hashes, 15.58 khash/s
[2018-03-04 13:27:39] accepted: 29/29 (100.00%), 15.58 khash/s (yay!!!)
[2018-03-04 13:28:14] thread 0: 539904 hashes, 15.55 khash/s
[2018-03-04 13:28:14] accepted: 30/30 (100.00%), 15.55 k1hash/s (yay!!!)

PS. 终结一个 screen ,切入该 screen 结束正在运行的程序, Ctrl + D

3. 应用

解决一下上次的遗留问题

root@xkfx:~# screen -dmS myChatroomServer

root@xkfx:~# screen -r myChatroomServer

root@xkfx:~# java -jar main.jar
The server is listening on 10000 port ...

[detached from 2586.myChatroomServer]

操作完后断开 ssh 测试:

原文地址:https://www.cnblogs.com/xkxf/p/8504302.html