Daemonizing processes on Linux

Process and peripheral concepts

TTY (virtual terminal) | -Session | -Process group | -Process

"TTY = session 1> N process group 1> N process"

One of the processes is a session leader, and several of them are process group leaders.

session

A login session associated with a TTY. It is a group of one or more process groups, and the process that becomes the session leader has the role of interacting with the control terminal and terminating all child processes when the terminal is disconnected. Process groups can only be created within the session to which they belong.

Process group

A collection of processes that can send signals to other processes. The member has the process ID of the process group leader as the group ID. Call setpgid () or setsid () to become the process group leader.

fork() Calling this function duplicates the process. If the return value is 0, it is processed by the child process, and if the return value is 0 or more, it is processed by the parent process. The two run at the same time with the same source code. Therefore, it is necessary to branch with an if statement and write two source codes, one for the parent process and one for the child process.

Implementation

#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>

#include <fcntl.h>
#include <signal.h>
#include <stdlib.h>
#include <sysexits.h>
#include <unistd.h>
#include <syslog.h>

#define MAXFD 64

int demonize(int chdir_flg){

    int i = 0;
    int fd = 0;
    pid_t pid = 0;


    //------------------------------------------------------
    //Status.
    //Parent process when the program starts(shell)Have a TTY.
    //------------------------------------------------------
    
    
    //------------------------------------------------------
    //Create a child process to detach the parent and return control to the shell.
    //------------------------------------------------------
    if((pid = fork()) == -1){

        return -1;

    //Parent process terminates after creating child process.
    }else if(pid != 0){

        //Don't call user-defined cleanup functions_exit()I do.
        _exit(0);
    }
    
    
    //------------------------------------------------------
    //Status.
    //Only child processes, but still retain TTY.
    //------------------------------------------------------
    

    //------------------------------------------------------
    //Separate TTY to become session leader and process group leader.
    //------------------------------------------------------
    setsid();
    

    //------------------------------------------------------
    //Ignore HUP signal.
    //Because a HUP signal can be sent to the child when the parent dies.
    //------------------------------------------------------
    signal(SIGHUP, SIG_IGN);
    

    //------------------------------------------------------
    //Status.
    //Since it is a session leader at this rate, if you open a TTY, that TTY will be associated..
    //------------------------------------------------------
    
    
    //------------------------------------------------------
    //Parent process(Session group leader)To disconnect.
    //Becoming a parentless, tty, and session leader.
    //------------------------------------------------------
    if((pid = fork()) == 0){
        //End child process.
        _exit(0);
    }
    


    //------------------------------------------------------
    //Prepare to run as a daemon.
    //------------------------------------------------------

    //Change current directory.
    if(chdir_flg == 0){
        
        //Move to root directory.
        chdir("/");
    }
    

        
    //Close all file descriptors inherited from parent.
    for(i = 0; i < MAXFD; i++){
        close(i);
    }
        
    // stdin,stdout,stderr dev/Open with null.
    //If you just close the descriptor, these outputs will result in an error, so dev/Redirect to null.
    if((fd = open("/dev/null", O_RDWR, 0) != -1)){
        
        //File descriptor replication.
        //0 of this process,1,Dev pointed to 2 by fd/Point to null.
        dup2(fd, 0);
        dup2(fd, 1);
        dup2(fd, 2);
        if(fd < 2){
            close(fd);
        }
    }
    
    return (0);

}

int main(int argc, const char * argv[]) {

    char buf[256];
    demonize(1);
    
    //View current directory.
    syslog(LOG_USER | LOG_NOTICE, "demon:cwd=%s¥n", getcwd(buf, sizeof(buf)));
    
    return 0;
}

It can be daemonized just by calling demonstrate () with the main () function. If you write a command to start a daemonized program in "/etc/rc.local", you can start it in the background when the server starts.

reference

["Linux Network Programming Bible"](http://www.amazon.co.jp/Linux Network Programming Bible-Mitsuyuki Omata-ebook/dp/B00O8GIL62/ref=sr_1_1?ie=UTF8&qid=1429337305&sr=8-1&keywords= linux + network programming bible) Scyphus Draft — How to make a daemon

Recommended Posts

Daemonizing processes on Linux
jblas on Arch Linux
Linux (WSL) on Windows
NAT router on Linux
Develop .NET on Linux
Wake on lan on Linux
Monitor traffic on Linux
Update vscode on linux
Try NeosVR on Linux
Check capacity on Linux
LiveUSB creation on Linux
Linux operation on Win10
NTP configuration memo on Linux
Install Linux on your Chromebox
Downgrade Mcomix on Arch Linux
About LINUX files and processes
Monitor disk usage on Linux
Use Github Desktop on Linux
Install the JDK on Linux
Elixir = Comfortable on Linux Mint
Recording and playback on Linux
Check TTL on Linux router
Read core voltage on Linux
Put jenv on Amazon Linux
Easy df command on Linux
Linux on Windows -1-: debian introduction
Install tomcat 5.5 on Amazon Linux.
Introducing Elixir on Linux Mint
Use sshpass on Amazon linux2
Install Homebrew on Amazon Linux 2
Paste the link on linux
Install strongSwan 5.9.1 on Amazon Linux 2
Linux environment construction (on WSL environment)
Run FreeBSD on Linux + qemu
Use Linux on Windows 10 (WSL2)
Setting up OpenSSH on Arch Linux
Use host.docker.internal on linux (docker-compose required)
Install Python Pillow on Amazon Linux
Easy copy to clipboard on Linux
Install oracle java8 on amazon linux2
Try installing OpenAM on Amazon Linux
WSL2 ~ Linux on Windows ~ (Part 1: Introduction)
Install CUDA on Linux Mint Mate 20
Install Arch Linux on DeskMini A300
Completion of docker command on Linux
Run a Linux server on GCP
How to install VMware-Tools on Linux
View disk usage on personal Linux
Install pyenv on EC2 (Amazon Linux)
[Linux] I installed CentOS on VirtualBox
Enjoy edge computing on Alpine Linux
Rip Music CDs on Arch Linux
Create a Linux environment on Windows 10
Make Live USB on Alpine Linux
Linux
[Linux] Docker environment construction on Redhat
Use Chrome Remote Desktop on Linux
[Note] Install Imagick on Amazon Linux2
[Note] Run Django on Amazon Linux 2
Run docker-compose on Amazon Linux2 on ARM64
Introduce Python 3.5.2 environment on Amazon Linux