nohup 命令
Linux下從shell啓動的前臺程序屬於當前shell的子進程,儘管可以在命令後加上 & 符號,使得其在後臺運行,但當登出shell後,仍舊會將其終止。
如何才能在登出shell後,仍然令它繼續運行呢?一種方法是使用 nohup 命令。
命令如:
nohup your_program >program.runlog 2>&1 &
實驗
先寫一段可以一直運行着的程序:
// main.cpp
#include <iostream>
#include <thread>
#include <chrono>
int main()
{
auto duration = std::chrono::milliseconds(1000); // 1s
while (true) {
std::cout << "Program is running..." << std::endl;
std::this_thread::sleep_for(duration);
}
return 0;
}
編譯:g++ -std=c++11 main.cpp
後臺運行:
$ nohup ./a.out >test.runlog 2>&1 &
關閉終端,然後重新登入,查看進程還在運行:ps aux | grep a.out
查看進程在持續工作,輸出內容:tail -f test.runlog
最後可以用 kill 命令殺掉測試程序。