dwm-meillo

view util.c @ 6:e0cefb3981c8

implemented pipe_spawn
author Anselm R. Garbe <garbeam@wmii.de>
date Tue, 11 Jul 2006 11:10:05 +0200
parents e5018cae273f
children d567f430a81d
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 setsid();
97 if(dpy)
98 close(ConnectionNumber(dpy));
99 execlp(shell, "shell", "-c", cmd, NULL);
100 fprintf(stderr, "gridwm: execvp %s", cmd);
101 perror(" failed");
102 }
103 exit (0);
104 }
105 wait(0);
106 }
108 void
109 pipe_spawn(char *buf, unsigned int len, Display *dpy, const char *cmd)
110 {
111 unsigned int l, n;
112 int pfd[2];
114 if(!shell && !(shell = getenv("SHELL")))
115 shell = "/bin/sh";
117 if(!cmd)
118 return;
120 if(pipe(pfd) == -1) {
121 perror("pipe");
122 exit(1);
123 }
125 if(fork() == 0) {
126 setsid();
127 if(dpy)
128 close(ConnectionNumber(dpy));
129 dup2(pfd[1], STDOUT_FILENO);
130 close(pfd[0]);
131 close(pfd[1]);
132 execlp(shell, "shell", "-c", cmd, NULL);
133 fprintf(stderr, "gridwm: execvp %s", cmd);
134 perror(" failed");
135 }
136 else {
137 n = 0;
138 close(pfd[1]);
139 while(l > n) {
140 if((l = read(pfd[0], buf + n, len - n)) < 1)
141 break;
142 n += l;
143 }
144 close(pfd[0]);
145 buf[n - 1] = 0;
146 }
147 wait(0);
148 }