int backend(int pfd) { signal(SIGTERM, sig); for(;;) { ssize_t res; int cmd, tmp; /* get command */ cmd = 0; if(read(pfd, &cmd, 1) == -1 && errno != EINTR) { perror("pipe read blew up in my face! wtf"); return -1; } switch(cmd) { case CMD_PING: tmp = (dpid = get_daemon_pid()) != -1; write(pfd, &tmp, 1); break; case CMD_CFG: { char *buf = (char*)&cfg; int sz = sizeof cfg; while(sz && (res = read(pfd, buf, sz)) > 0) { buf += res; sz -= res; } update_cfg(); } break; case CMD_STARTX: case CMD_STOPX: if(dpid == -1) { if((dpid = get_daemon_pid()) == -1) { return -1; } } if(kill(dpid, cmd == CMD_STARTX ? SIGUSR1 : SIGUSR2) == -1) { if(errno != EPERM) { dpid = -1; kill(getppid(), SIGUSR2); } } break; default: fprintf(stderr, "unknown CMD: %d\n", (int)cmd); break; } } return 0; }
int is_myself_running(const char *pid_path) { int retVal = -1; struct stat fStatBuf; retVal = stat(pid_path, &fStatBuf); if(0 == retVal) { pid_t pid = -1; pid = get_daemon_pid(pid_path); if (pid > 0) /*Process pid exist*/ { if (kill(pid, 0) == 0) { logs(LOG_CRIT, "file \"%s\" already exists.\n" "\t\tAnother program (pid: %d) seems to be running.\n", pid_path, pid); return RUNNING; } else /*Send signal to the old process get no reply.*/ { logs(LOG_DEBG, "Program (pid: %d) seems exit. Do some clean work now.\n", pid); remove(pid_path); return NOT_RUNNING; } } else if(0 == pid) { logs(LOG_INFO, "Last Running PID file is empty, clean it now.\n"); remove(pid_path); return NOT_RUNNING; } else /*Read pid from file "pid_path" failure*/ { logs(LOG_CRIT, "File \"%s\" already exists, but I can not read the process pid." "Maybe another program is running?\n" "If the program is not running, remove it and try again.\n" , pid_path); return RUNNING; } } return NOT_RUNNING; }
static int query_x11(void) { Display *dpy; Window win, root_win; XTextProperty wname; Atom type, command_event; int fmt; unsigned long nitems, bytes_after; unsigned char *prop; if(!(dpy = XOpenDisplay(0))) { return 0; } root_win = DefaultRootWindow(dpy); if((command_event = XInternAtom(dpy, "CommandEvent", True)) == None) { XCloseDisplay(dpy); return 0; } XGetWindowProperty(dpy, root_win, command_event, 0, 1, False, AnyPropertyType, &type, &fmt, &nitems, &bytes_after, &prop); if(!prop) { XCloseDisplay(dpy); return 0; } win = *(Window*)prop; XFree(prop); if(!XGetWMName(dpy, win, &wname) || strcmp("Magellan Window", (char*)wname.value) != 0) { XCloseDisplay(dpy); return 0; } XCloseDisplay(dpy); /* found a magellan window, still it might belong to the 3dxsrv driver */ if(get_daemon_pid() == -1) { return 0; } /* this could still mean that the daemon crashed and left behind the pidfile... */ return 1; /* ... but wtf */ }
static int update_cfg(void) { if(write_cfg(CFGFILE, &cfg) == -1) { return -1; } if(dpid == -1) { if((dpid = get_daemon_pid()) == -1) { return -1; } } if(kill(dpid, SIGHUP) == -1 && errno != EPERM) { dpid = -1; /* invalidate pid, will be searched again next time */ return -1; } return 0; }