zoukankan      html  css  js  c++  java
  • 使用 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 命令杀掉测试程序。

  • 相关阅读:
    hud 1397
    hdu 1211
    hdu 1124
    hdu 1104
    1788
    hdu 1796
    sdut 2169
    hdu 1019
    $http post 取不到数据
    sql
  • 原文地址:https://www.cnblogs.com/demon90s/p/15466132.html
Copyright © 2011-2022 走看看