aewl

view util.c @ 10:703255003abb

changed how manage client works
author Anselm R. Garbe <garbeam@wmii.de>
date Tue, 11 Jul 2006 13:02:22 +0200
parents e0cefb3981c8
children ea9c08ec4b48
line source
1 /*
2 * (C)opyright MMVI Anselm R. Garbe <garbeam at gmail dot com>
3 * See LICENSE file for license details.
4 */
6 #include <stdarg.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 #include <sys/types.h>
11 #include <sys/wait.h>
12 #include <unistd.h>
14 #include "util.h"
16 static char *shell = NULL;
18 void
19 error(char *errstr, ...) {
20 va_list ap;
21 va_start(ap, errstr);
22 vfprintf(stderr, errstr, ap);
23 va_end(ap);
24 exit(1);
25 }
27 static void
28 bad_malloc(unsigned int size)
29 {
30 fprintf(stderr, "fatal: could not malloc() %d bytes\n",
31 (int) size);
32 exit(1);
33 }
35 void *
36 emallocz(unsigned int size)
37 {
38 void *res = calloc(1, size);
39 if(!res)
40 bad_malloc(size);
41 return res;
42 }
44 void *
45 emalloc(unsigned int size)
46 {
47 void *res = malloc(size);
48 if(!res)
49 bad_malloc(size);
50 return res;
51 }
53 void *
54 erealloc(void *ptr, unsigned int size)
55 {
56 void *res = realloc(ptr, size);
57 if(!res)
58 bad_malloc(size);
59 return res;
60 }
62 char *
63 estrdup(const char *str)
64 {
65 void *res = strdup(str);
66 if(!res)
67 bad_malloc(strlen(str));
68 return res;
69 }
71 void
72 failed_assert(char *a, char *file, int line)
73 {
74 fprintf(stderr, "Assertion \"%s\" failed at %s:%d\n", a, file, line);
75 abort();
76 }
78 void
79 swap(void **p1, void **p2)
80 {
81 void *tmp = *p1;
82 *p1 = *p2;
83 *p2 = tmp;
84 }
86 void
87 spawn(Display *dpy, const char *cmd)
88 {
89 if(!shell && !(shell = getenv("SHELL")))
90 shell = "/bin/sh";
92 if(!cmd)
93 return;
94 if(fork() == 0) {
95 if(fork() == 0) {
96 if(dpy)
97 close(ConnectionNumber(dpy));
98 setsid();
99 fprintf(stderr, "gridwm: execlp %s %s -c %s", shell, shell, cmd);
100 execlp(shell, shell, "-c", cmd, NULL);
101 fprintf(stderr, "gridwm: execlp %s", cmd);
102 perror(" failed");
103 }
104 exit (0);
105 }
106 wait(0);
107 }
109 void
110 pipe_spawn(char *buf, unsigned int len, Display *dpy, const char *cmd)
111 {
112 unsigned int l, n;
113 int pfd[2];
115 if(!shell && !(shell = getenv("SHELL")))
116 shell = "/bin/sh";
118 if(!cmd)
119 return;
121 if(pipe(pfd) == -1) {
122 perror("pipe");
123 exit(1);
124 }
126 if(fork() == 0) {
127 if(dpy)
128 close(ConnectionNumber(dpy));
129 setsid();
130 dup2(pfd[1], STDOUT_FILENO);
131 close(pfd[0]);
132 close(pfd[1]);
133 execlp(shell, shell, "-c", cmd, NULL);
134 fprintf(stderr, "gridwm: execlp %s", cmd);
135 perror(" failed");
136 }
137 else {
138 n = 0;
139 close(pfd[1]);
140 while(l > n) {
141 if((l = read(pfd[0], buf + n, len - n)) < 1)
142 break;
143 n += l;
144 }
145 close(pfd[0]);
146 buf[n - 1] = 0;
147 }
148 wait(0);
149 }