How to prevent a background process from being stopped after closing SSH client in Linux

前端 未结 20 1338
悲&欢浪女
悲&欢浪女 2020-11-22 06:16

I\'m working on a Linux machine through SSH (Putty). I need to leave a process running during the night, so I thought I could do that by starting the process in background (

20条回答
  •  情话喂你
    2020-11-22 07:13

    Accepted answer suggest using nohup. I would rather suggest using pm2. Using pm2 over nohup has many advantages, like keeping the application alive, maintain log files for application and lot more other features. For more detail check this out.

    To install pm2 you need to download npm. For Debian based system

    sudo apt-get install npm
    

    and for Redhat

    sudo yum install npm
    

    Or you can follow these instruction. After installing npm use it to install pm2

    npm install pm2@latest -g
    

    Once its done you can start your application by

    $ pm2 start app.js              # Start, Daemonize and auto-restart application (Node)
    $ pm2 start app.py              # Start, Daemonize and auto-restart application (Python)
    

    For process monitoring use following commands:

    $ pm2 list                      # List all processes started with PM2
    $ pm2 monit                     # Display memory and cpu usage of each app
    $ pm2 show [app-name]           # Show all informations about application
    

    Manage processes using either app name or process id or manage all processes together:

    $ pm2 stop     
    $ pm2 restart  
    $ pm2 delete   
    

    Log files can be found in

    $HOME/.pm2/logs #contain all applications logs
    

    Binary executable files can also be run using pm2. You have to made a change into the jason file. Change the "exec_interpreter" : "node", to "exec_interpreter" : "none". (see the attributes section).

    #include 
    #include   //No standard C library
    int main(void)
    {
        printf("Hello World\n");
        sleep (100);
        printf("Hello World\n");
    
        return 0;
    }
    

    Compiling above code

    gcc -o hello hello.c  
    

    and run it with np2 in the background

    pm2 start ./hello
    

提交回复
热议问题