Util: Fix spawn

This commit is contained in:
Martin Duquesnoy
2011-01-10 19:31:42 +01:00
parent 18e97d3e1e
commit 056cb5daf6

View File

@@ -253,14 +253,15 @@ alias_to_str(char *conf_choice)
* \param cmd Command * \param cmd Command
* \return child pid * \return child pid
*/ */
pid_t int
spawn(const char *format, ...) spawn(const char *format, ...)
{ {
char *sh = NULL; char *sh = NULL;
char cmd[512]; char cmd[512];
va_list ap; va_list ap;
pid_t pid, ret;
int p[2];
size_t len; size_t len;
pid_t pid;
va_start(ap, format); va_start(ap, format);
len = vsnprintf(cmd, sizeof(cmd), format, ap); len = vsnprintf(cmd, sizeof(cmd), format, ap);
@@ -275,18 +276,48 @@ spawn(const char *format, ...)
if(!(sh = getenv("SHELL"))) if(!(sh = getenv("SHELL")))
sh = "/bin/sh"; sh = "/bin/sh";
if (pipe(p) == -1)
{
warn("pipe");
return -1;
}
if((pid = fork()) == 0) if((pid = fork()) == 0)
{ {
if(dpy) close(p[0]);
close(ConnectionNumber(dpy)); if((pid = fork()) == 0)
setsid(); {
execl(sh, sh, "-c", cmd, (char*)NULL); if(dpy)
err(1, "execl(%s)", cmd); close(ConnectionNumber(dpy));
} setsid();
if (pid == -1) execl(sh, sh, "-c", cmd, (char*)NULL);
warn("fork()"); exit(EXIT_FAILURE);
}
return pid; if (sizeof(pid_t) != write(p[1], &pid, sizeof(pid_t)))
warn("write");
close(p[1]);
exit(EXIT_SUCCESS);
}
else if (pid != -1)
{
close(p[1]);
if (sizeof(pid_t) != read(p[0], &ret, sizeof(pid_t)))
{
warn("read");
ret = -1;
}
close(p[0]);
waitpid(pid, NULL, 0);
}
else
{
warn("fork");
ret = -1;
}
return ret;
} }
/** Swap two pointer. /** Swap two pointer.