使用 nohup 命令令程序在后台运行

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 命令杀掉测试程序。

posted @ 2021-10-26 15:44  Demon90s  阅读(705)  评论(0编辑  收藏  举报