• cron 程序无法使用
  • 公司 dcron 平台 任务不方便管理,页面只能显示一个 porject和token
    • 要么不停的切换 project 在浏览器
    • 要么所有的任务都压缩到一个project中,因为任务还无法删除,目前有近200个任务
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>


#define DEBUG 0
#define YII_APP_BASE_DIR "/var/www/app/yii"

typedef struct job{
    char* yii_cmd;

    pid_t pid;
//    char* stdout_file;
//    char* stderr_file;
    int running;
}job_t;


int process_job(job_t* job) {
    pid_t job_pid = fork();

    printf("%s %x\n", __FUNCTION__, job);
    if(job_pid == 0) {
        printf("---->task %s process id: %d %d\n",job->yii_cmd, getpid(), getppid());
        execlp("php70", "php70",YII_APP_BASE_DIR, job->yii_cmd, NULL);
        perror("execlp");
    
    } else {
      
        printf("------------>task manager process id: %d %d\n", getpid(), getppid());
        job->running = 1;
        job->pid = job_pid;
        return job_pid;
    } 
}


void deamanize(){
  
    pid_t pid =  fork();

#if 1
    printf("aaaaa");
    fflush(stdout);
    int fd = open("/dev/null",O_RDWR);
    dup2(fd,0);
    dup2(fd, 1);
    dup2(fd, 2);
#endif

  
    if(pid !=0){
        exit(0);
    }

    setsid();
    umask(0);
    chdir("/");

    printf("%d %d\n", getpid(), getppid());
}

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

    job_t jobs[] = {
        {
            .yii_cmd = "test/test",
            .running = 0,
            .pid = 0,
        },
    };

    int jobs_num = sizeof(jobs)/sizeof(job_t);

    printf("job_nums:%d\n", jobs_num);

    while(1){
        sleep(60);
        job_t* jp = jobs;
        int i = 0;

        printf("%x %d\n", jp, i);
        for(i = 0; i < jobs_num; ++i, jp++)
        {
            if(jp->running){
                int ret_pid = waitpid(jp->pid,NULL, WNOHANG);
                printf("waitpid ret_val:%d\n", ret_pid);
                if(ret_pid == jp->pid){
                    jp->running = 0;
                }else if (ret_pid == 0){
                    
                }else if (ret_pid == -1){
                    if(errno == ECHILD) {
                        jp->running = 0;
                    }
                }
            }

            if(!jp->running){
                process_job(&jobs[i]);
            }
        }
    }
    
    return 0;
}