util.c (2962B)
1 #include <signal.h> 2 #include <stdio.h> 3 #include <stdlib.h> 4 #include <unistd.h> 5 6 #include "util.h" 7 8 void 9 cspawn(char *const *arg) 10 { 11 setsid(); 12 execvp(arg[0], arg); 13 perror("cspawn - execvp"); 14 _exit(127); 15 } 16 17 void 18 csigself(int sig, int sigval) 19 { 20 union sigval sv; 21 22 sig += SIGRTMIN; 23 sv.sival_int = sigval; 24 if (sigqueue(pid, sig, sv) == -1) { 25 perror("csigself - sigqueue"); 26 exit(1); 27 } 28 } 29 30 /* getcmdout doesn't null terminate cmdout 31 * make sure that terminal newline character is handled if the command spits one */ 32 size_t 33 getcmdout(char *const *arg, char *cmdout, size_t cmdoutlen) 34 { 35 int fd[2]; 36 size_t trd; 37 ssize_t rd; 38 39 if (pipe(fd) == -1) { 40 perror("getcmdout - pipe"); 41 cleanup(); 42 exit(1); 43 } 44 switch (fork()) { 45 case -1: 46 perror("getcmdout - fork"); 47 cleanup(); 48 exit(1); 49 case 0: 50 close(ConnectionNumber(dpy)); 51 close(fd[0]); 52 if (fd[1] != STDOUT_FILENO) { 53 if (dup2(fd[1], STDOUT_FILENO) != STDOUT_FILENO) { 54 perror("getcmdout - child - dup2"); 55 exit(1); 56 } 57 close(fd[1]); 58 } 59 execvp(arg[0], arg); 60 perror("getcmdout - child - execvp"); 61 _exit(127); 62 default: 63 close(fd[1]); 64 trd = 0; 65 do 66 rd = read(fd[0], cmdout + trd, cmdoutlen - trd); 67 while (rd > 0 && (trd += rd) < cmdoutlen); 68 if (rd == -1) { 69 perror("getcmdout - read"); 70 cleanup(); 71 exit(1); 72 } 73 close(fd[0]); 74 } 75 return trd; 76 } 77 78 int 79 readint(const char *path, int *var) { 80 FILE *fp; 81 82 if (!(fp = fopen(path, "r"))) 83 return 0; 84 if (fscanf(fp, "%d", var) != 1) { 85 fclose(fp); 86 return 0; 87 } 88 fclose(fp); 89 return 1; 90 } 91 92 void 93 uspawn(char *const *arg) 94 { 95 switch (fork()) { 96 case -1: 97 perror("uspawn - fork"); 98 cleanup(); 99 exit(1); 100 case 0: 101 close(ConnectionNumber(dpy)); 102 setsid(); 103 execvp(arg[0], arg); 104 perror("uspawn - child - execvp"); 105 _exit(127); 106 } 107 }