Linux 下让你的C程序在后台运行

void setdaemon(void)
{
    pid_t pid;

    
if((pid = fork()) < 0){   
        mylog(
"fork1 failed");
        exit(
-1);
    }

    
if (pid){   
        exit(
0);
    }   

    setsid();

    
if ((pid = fork()) < 0){   
        fprintf(stderr, 
"fork2 failed");
        exit(
-1);
    }   

    
if (pid){   
        exit(
0);
    }   
    write_pidfile();
    
/*
    chdir("/");
    umask(0);
    
*/
}

void write_pidfile(void)
{
    
int  fd;
    
char buff[20];
    
if ((fd = open("send.pid", O_CREAT | O_WRONLY, 0600)) >= 0)
    {
        bzero(buff, 
sizeof(buff));
        sprintf(buff, 
"%5d\n", (int)getpid());
        
if (write(fd, buff, strlen(buff)) == -1)
            mylog(
"Error writing to pid file send.pid");
        (
void)close(fd);
        
return;
    }
}
原文地址:https://www.cnblogs.com/taobataoma/p/875596.html