int daemond_pid_lock(daemond_pid * pid) { struct stat sb; int r,err; pid_t oldpid; FILE *f; daemond_say(pid->d, "lock %s", pid->pidfile); if( stat(pid->pidfile, &sb) == -1 ) { err = errno; ewarn("no pid"); switch(err) { case ENOENT: r = daemond_pid_openlocked( pid, 0 ); break; default: warn("shit!"); } } else { //debug("have pid"); f = fopen(pid->pidfile,"r"); if (!f) { die("Can't open old pidfile `%s' for reading: %s",pid->pidfile, ERR); } if( fscanf(f,"%d",&oldpid) > 0 ) { //debug("got old pid: %d",oldpid); if( kill(oldpid,0) == 0 ) { //warn("old process %d still alive",oldpid); pid->oldpid = oldpid; return 0; } else { //daemond_say(pid->d, "<y>stalled pidfile old pid %d is invalid", oldpid); } } else { daemond_say(pid->d, "<r>can't read pidfile contents"); } r = daemond_pid_openlocked( pid, 0 ); } if (pid->locked) { //if (pid->verbose) //debug( "pidfile `%s' was locked", pid->pidfile ); if( flock(pid->fd, LOCK_EX|LOCK_NB) == -1) { die("Relock pidfile `%s' failed: %s",pid->pidfile, strerror(errno)); } daemond_pid_write(pid); return 1; } return 0; }
int main(int argc, char **argv) { static jsd_conf cfg[JSD_END]; char *script = NULL, *command = NULL, *pidfile = NULL; int opt; int config; daemond_init(&d); d.use_pid = 1; d.detach = 1; d.pid.verbose = 1; if (argc < 2) goto help; while((opt = getopt(argc, argv, "c:C:p:vh")) != -1) { switch (opt) { case 'c': script = optarg; break; case 'C': command = optarg; break; case 'p': pidfile = optarg; break; case 'v': d.detach = 0; break; case 'h': goto help; break; } } if (!command) goto help; if (!script) goto help; lua_State *LUA = jsd_lua_init(script); if (pidfile) d.pid.pidfile = pidfile; cfg[JSD_SERVER].xattr = malloc(sizeof(jsd_server_conf)); cfg[JSD_MYSQL].xattr = malloc(sizeof(jsd_db_conf)); ((jsd_server_conf *)cfg[JSD_SERVER].xattr)->d = &d; for (config = 0; config < JSD_END; ++config) { jsd_config_lua(LUA, cfg, config); } lua_close(LUA); /* Demonize */ daemond_cli_run(&d.cli, 1, &command); daemond_say(&d, "<g>Starting</>... (pidfile = %s, pid = <y>%d</>)", d.pid.pidfile, getpid()); daemond_daemonize(&d); daemond_master(&d); daemond_say(&d, "Forked: %d",getpid()); jsd_http_server(cfg); /** * FIX ME, need free all data from array cfg free((void*)cfg->handler); free((void*)cfg->host); free((void*)cfg->password); free((void*)cfg->user); */ return 0; help: usage(); return 1; }