Last active
June 24, 2021 07:59
-
-
Save nufeng1999/57f76a6cf1c9447c7359f2b30da2763e to your computer and use it in GitHub Desktop.
[daemon函数] #gcc #daemon
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // vim: syntax=c | |
| int daemon( int nochdir, int noclose ) | |
| { | |
| pid_t pid; | |
| if ( !nochdir && chdir("/") != 0 ) //if nochdir=0,change dir to "/" | |
| return -1; | |
| if ( !noclose ) //if noclose is 0 | |
| { | |
| int fd = open("/dev/null", O_RDWR); | |
| if ( fd < 0 ) | |
| return -1; | |
| /* Redirect standard input,output,error to /dev/null. */ | |
| dup(fd, 0); | |
| dup(fd, 1); | |
| dup(fd, 2); | |
| close(fd); | |
| } | |
| pid = fork(); //Create child process. | |
| if (pid < 0) //fail | |
| return -1; | |
| if (pid > 0) | |
| _exit(0); //Return to the parent process, then the parent process exits, and the child process becomes a real orphan process. | |
| if ( setsid() < 0 ) //Create a new session and make the subprocess the root process of the new session | |
| return -1; | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment