dwm-meillo

diff 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 diff
     1.1 --- a/util.c	Mon Jul 10 22:16:48 2006 +0200
     1.2 +++ b/util.c	Tue Jul 11 11:10:05 2006 +0200
     1.3 @@ -13,6 +13,8 @@
     1.4  
     1.5  #include "util.h"
     1.6  
     1.7 +static char *shell = NULL;
     1.8 +
     1.9  void
    1.10  error(char *errstr, ...) {
    1.11  	va_list ap;
    1.12 @@ -82,19 +84,65 @@
    1.13  }
    1.14  
    1.15  void
    1.16 -spawn(Display *dpy, const char *shell, const char *cmd)
    1.17 +spawn(Display *dpy, const char *cmd)
    1.18  {
    1.19 -	if(!cmd || !shell)
    1.20 +	if(!shell && !(shell = getenv("SHELL")))
    1.21 +		shell = "/bin/sh";
    1.22 +
    1.23 +	if(!cmd)
    1.24  		return;
    1.25  	if(fork() == 0) {
    1.26  		if(fork() == 0) {
    1.27 +			setsid();
    1.28  			if(dpy)
    1.29  				close(ConnectionNumber(dpy));
    1.30 -			execl(shell, shell, "-c", cmd, (const char *)0);
    1.31 -			fprintf(stderr, "gridwm: execl %s", shell);
    1.32 +			execlp(shell, "shell", "-c", cmd, NULL);
    1.33 +			fprintf(stderr, "gridwm: execvp %s", cmd);
    1.34  			perror(" failed");
    1.35  		}
    1.36  		exit (0);
    1.37  	}
    1.38  	wait(0);
    1.39  }
    1.40 +
    1.41 +void
    1.42 +pipe_spawn(char *buf, unsigned int len, Display *dpy, const char *cmd)
    1.43 +{
    1.44 +	unsigned int l, n;
    1.45 +	int pfd[2];
    1.46 +
    1.47 +	if(!shell && !(shell = getenv("SHELL")))
    1.48 +		shell = "/bin/sh";
    1.49 +
    1.50 +	if(!cmd)
    1.51 +		return;
    1.52 +
    1.53 +	if(pipe(pfd) == -1) {
    1.54 +		perror("pipe");
    1.55 +		exit(1);
    1.56 +	}
    1.57 +
    1.58 +	if(fork() == 0) {
    1.59 +		setsid();
    1.60 +		if(dpy)
    1.61 +			close(ConnectionNumber(dpy));
    1.62 +		dup2(pfd[1], STDOUT_FILENO);
    1.63 +		close(pfd[0]);
    1.64 +		close(pfd[1]);
    1.65 +		execlp(shell, "shell", "-c", cmd, NULL);
    1.66 +		fprintf(stderr, "gridwm: execvp %s", cmd);
    1.67 +		perror(" failed");
    1.68 +	}
    1.69 +	else {
    1.70 +		n = 0;
    1.71 +		close(pfd[1]);
    1.72 +		while(l > n) {
    1.73 +			if((l = read(pfd[0], buf + n, len - n)) < 1)
    1.74 +				break;
    1.75 +			n += l;
    1.76 +		}
    1.77 +		close(pfd[0]);
    1.78 +		buf[n - 1] = 0;
    1.79 +	}
    1.80 +	wait(0);
    1.81 +}