如何设置精灵|守护进程


/*
 * =====================================================================================
 *
 *       Filename:  daemon.c
 *
 *    Description:  守护进程
 *
 *        Version:  1.0
 *        Created:  2012年04月24日 15时47分18秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *        Company:  
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <syslog.h>
#include <fcntl.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <signal.h>


void daemonize(const char *cmd)
{
    int i, fd0, fd1, fd2;
    pid_t pid;
    struct rlimit  r2;
    struct sigaction  sa;
    
    /* Clear file creation mask */
    umask(0);


    /* Get maximum number of file descriptors */
    if((getrlimit(RLIMIT_NOFILE, &r2)) < 0)
        printf("can't get file limit");


    /* Become a session leader to lose controlling TTY. */
    if((pid = fork()) < 0)
    {
        printf("fork err!\n");
    }
    else if(pid == 0)       //child
    {
       ; 
    }
    else                   //parent
    {
       exit(0); 
    }


    setsid();


    /* Ensure future opens won't allocate controlling TTYs. */
    sa.sa_handler = SIG_IGN;
    sigemptyset(&sa.sa_mask);
    sa.sa_flags = 0;
    if(sigaction(SIGHUP, &sa, NULL) < 0)
        printf("sigaction err !\n");


    if((pid = fork()) < 0)
    {
        printf("fork err again !\n");
    }
    else if(pid > 0)
    {
        exit(0);
    }


    /* Change the current working directory to the root so 
     * we won't prevent file systems from being unmounted.
     */
    if(chdir("/") < 0)
    {
        printf("chdir err !\n");
    }


    /* Close all open file descripters */
    if(r2.rlim_max = RLIM_INFINITY)
    {
        r2.rlim_max = 1024; 
    }


    for(i = 0; i < r2.rlim_max; i++)
    {
        close(i);    
    }


    /* Attach file descriptors 0, 1, 2 to /dev/null */
    fd0 = open("/dev/null", O_RDWR);
    fd1 = dup(0);
    fd2 = dup(0);


    /* Initialize the log file. */
    openlog(cmd, LOG_CONS, LOG_DAEMON);
    if(fd0 != 0 || fd1 != 1 || fd2 != 2)
    {
        syslog(LOG_ERR, "unexpected file descriptors %d %d %d\n", fd0, fd1, fd2);
        exit(1);
    }


}


int main(void)
{
    daemonize("daemon"); 


    while(1)sleep(1);
    return 0;
}

你可能感兴趣的:(如何设置精灵|守护进程)