service.c (2268B)
1 /* Service related operations 2 * 3 * Copyright (C) 2020 Cem Keylan <cem@ckyln.com> 4 * 5 * This program is free software: you can redistribute it and/or modify 6 * it under the terms of the GNU General Public License as published by 7 * the Free Software Foundation, either version 3 of the License, or 8 * (at your option) any later version. 9 * 10 * This program is distributed in the hope that it will be useful, 11 * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 * GNU General Public License for more details. 14 * 15 * You should have received a copy of the GNU General Public License 16 * along with this program. If not, see <https://www.gnu.org/licenses/>. 17 */ 18 #include <stdio.h> 19 #include <unistd.h> 20 #include <sys/stat.h> 21 22 #include "../util.h" 23 #include "../config.h" 24 25 service* 26 sv_init(service *sv, char *sv_name) 27 { 28 sprintf(sv->name, "%s", sv_name); 29 sprintf(sv->sysdir, "%s", getenv_fallback("SYSDIR", sysdir_default)); 30 sprintf(sv->rundir, "%s", getenv_fallback("RUNDIR", rundir_default)); 31 sprintf(sv->pidfile, "%s/%s/pid", sv->rundir, sv->name); 32 sprintf(sv->syspidfile, "%s/%s/syspid", sv->rundir, sv->name); 33 sprintf(sv->svfile, "%s/%s", sv->sysdir, sv_name); 34 sprintf(sv->svrundir, "%s/%s", sv->rundir, sv_name); 35 sprintf(sv->lockfile, "%s/%s/lock", sv->rundir, sv->name); 36 37 return sv; 38 } 39 40 void sv_start(service *sv) 41 { 42 char *arg_list[] = {"runsyssv", sv->svfile, NULL}; 43 switch(fork()) { 44 case 0: 45 setsid(); 46 execvp("runsyssv", arg_list); 47 perror("execvp"); 48 break; 49 case -1: 50 perror("fork"); 51 break; 52 } 53 } 54 55 int sv_check(service *sv, int force) 56 { 57 /* If force is specified '1', this will return the actual service status 58 * regardless of the lockfile. The lockfile serves the purpose of 59 * stopping services and making sure they are not restarted. 60 */ 61 pid_t pid; 62 struct stat sb; 63 64 if (lstat(sv->lockfile, &sb) == 0) { 65 if (force == 1) 66 return -1; 67 else 68 return 0; 69 } 70 71 pid = getsyspid(sv); 72 73 if (pid < 0 || checkprocess(pid) != 0) 74 return -1; 75 76 return 0; 77 } 78 79 int sv_writelock(char *file, int sig) 80 { 81 FILE *lockfile; 82 83 lockfile = fopen(file, "w"); 84 if (lockfile == NULL) { 85 perror(file); 86 return -1; 87 } 88 fprintf(lockfile, "%d\n", sig); 89 fclose(lockfile); 90 91 return 0; 92 }