dwm-meillo
view util.c @ 16:359b6e563b95
several changes, new stuff
author | Anselm R. Garbe <garbeam@wmii.de> |
---|---|
date | Tue, 11 Jul 2006 18:53:41 +0200 |
parents | 00d4d52b231f |
children | 2e0fb4130bfb |
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 void
17 error(char *errstr, ...) {
18 va_list ap;
19 va_start(ap, errstr);
20 vfprintf(stderr, errstr, ap);
21 va_end(ap);
22 exit(1);
23 }
25 static void
26 bad_malloc(unsigned int size)
27 {
28 fprintf(stderr, "fatal: could not malloc() %d bytes\n",
29 (int) size);
30 exit(1);
31 }
33 void *
34 emallocz(unsigned int size)
35 {
36 void *res = calloc(1, size);
37 if(!res)
38 bad_malloc(size);
39 return res;
40 }
42 void *
43 emalloc(unsigned int size)
44 {
45 void *res = malloc(size);
46 if(!res)
47 bad_malloc(size);
48 return res;
49 }
51 void *
52 erealloc(void *ptr, unsigned int size)
53 {
54 void *res = realloc(ptr, size);
55 if(!res)
56 bad_malloc(size);
57 return res;
58 }
60 char *
61 estrdup(const char *str)
62 {
63 void *res = strdup(str);
64 if(!res)
65 bad_malloc(strlen(str));
66 return res;
67 }
69 void
70 failed_assert(char *a, char *file, int line)
71 {
72 fprintf(stderr, "Assertion \"%s\" failed at %s:%d\n", a, file, line);
73 abort();
74 }
76 void
77 swap(void **p1, void **p2)
78 {
79 void *tmp = *p1;
80 *p1 = *p2;
81 *p2 = tmp;
82 }
84 void
85 spawn(Display *dpy, char *argv[])
86 {
87 if(!argv || !argv[0])
88 return;
89 if(fork() == 0) {
90 if(fork() == 0) {
91 if(dpy)
92 close(ConnectionNumber(dpy));
93 setsid();
94 execvp(argv[0], argv);
95 fprintf(stderr, "gridwm: execvp %s", argv[0]);
96 perror(" failed");
97 }
98 exit (0);
99 }
100 wait(0);
101 }
103 void
104 pipe_spawn(char *buf, unsigned int len, Display *dpy, char *argv[])
105 {
106 unsigned int l, n;
107 int pfd[2];
109 if(!argv || !argv[0])
110 return;
112 if(pipe(pfd) == -1) {
113 perror("pipe");
114 exit(1);
115 }
117 if(fork() == 0) {
118 if(dpy)
119 close(ConnectionNumber(dpy));
120 setsid();
121 dup2(pfd[1], STDOUT_FILENO);
122 close(pfd[0]);
123 close(pfd[1]);
124 execvp(argv[0], argv);
125 fprintf(stderr, "gridwm: execvp %s", argv[0]);
126 perror(" failed");
127 }
128 else {
129 n = 0;
130 close(pfd[1]);
131 while(l > n) {
132 if((l = read(pfd[0], buf + n, len - n)) < 1)
133 break;
134 n += l;
135 }
136 close(pfd[0]);
137 buf[n < len ? n : len - 1] = 0;
138 }
139 wait(0);
140 }