bf02fd72540d39a0beca7022529b9ff4783cdcae
[ardour.git] / libs / pbd / system_exec.cc
1 /*
2     Copyright (C) 2010 Paul Davis
3     Copyright 2005-2008 Lennart Poettering
4     Author: Robin Gareus <robin@gareus.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20 */
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <errno.h>
25 #include <unistd.h>
26
27 #include <assert.h>
28 #include <dirent.h>
29
30 #ifdef __WIN32__
31 #include <windows.h>
32 #else
33 #include <fcntl.h>
34 #include <sys/types.h>
35 #include <sys/wait.h>
36 #include <sys/socket.h>
37 #include <sys/ioctl.h>
38 #include <sys/time.h>
39 #include <sys/resource.h>
40 #endif
41
42
43 #include "pbd/system_exec.h"
44
45 using namespace std;
46 void * interposer_thread (void *arg);
47
48 static void close_fd (int& fd) { if (fd >= 0) ::close (fd); fd = -1; }
49
50 #ifndef __WIN32__
51 /*
52  * This function was part of libasyncns.
53  * LGPL v2.1
54  * Copyright 2005-2008 Lennart Poettering
55  */
56 static int close_allv(const int except_fds[]) {
57         struct rlimit rl;
58         int fd;
59
60 #ifdef __linux__
61
62         DIR *d;
63
64         assert(except_fds);
65
66         if ((d = opendir("/proc/self/fd"))) {
67                 struct dirent *de;
68
69                 while ((de = readdir(d))) {
70                         int found;
71                         long l;
72                         char *e = NULL;
73                         int i;
74
75                         if (de->d_name[0] == '.')
76                                         continue;
77
78                         errno = 0;
79                         l = strtol(de->d_name, &e, 10);
80                         if (errno != 0 || !e || *e) {
81                                 closedir(d);
82                                 errno = EINVAL;
83                                 return -1;
84                         }
85
86                         fd = (int) l;
87
88                         if ((long) fd != l) {
89                                 closedir(d);
90                                 errno = EINVAL;
91                                 return -1;
92                         }
93
94                         if (fd < 3)
95                                 continue;
96
97                         if (fd == dirfd(d))
98                                 continue;
99
100                         found = 0;
101                         for (i = 0; except_fds[i] >= 0; i++)
102                                 if (except_fds[i] == fd) {
103                                                 found = 1;
104                                                 break;
105                                 }
106
107                         if (found) continue;
108
109                         if (close(fd) < 0) {
110                                 int saved_errno;
111
112                                 saved_errno = errno;
113                                 closedir(d);
114                                 errno = saved_errno;
115
116                                 return -1;
117                         }
118                 }
119
120                 closedir(d);
121                 return 0;
122         }
123
124 #endif
125
126         if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
127                 return -1;
128
129         for (fd = 0; fd < (int) rl.rlim_max; fd++) {
130                 int i;
131
132                 if (fd <= 3)
133                                 continue;
134
135                 for (i = 0; except_fds[i] >= 0; i++)
136                         if (except_fds[i] == fd)
137                                 continue;
138
139                 if (close(fd) < 0 && errno != EBADF)
140                         return -1;
141         }
142
143         return 0;
144 }
145 #endif /* not on windows */
146
147 void
148 SystemExec::init ()
149 {
150         pthread_mutex_init(&write_lock, NULL);
151         thread_active=false;
152         pid = 0;
153         pin[1] = -1;
154         nicelevel = 0;
155         envp = NULL;
156 #ifdef __WIN32__
157         stdinP[0] = stdinP[1] = INVALID_HANDLE_VALUE;
158         stdoutP[0] = stdoutP[1] = INVALID_HANDLE_VALUE;
159         stderrP[0] = stderrP[1] = INVALID_HANDLE_VALUE;
160 #endif
161 }
162
163 SystemExec::SystemExec (std::string c, std::string a)
164         : cmd(c)
165 {
166         init ();
167
168         argp = NULL;
169         make_envp();
170         make_argp(a);
171 }
172
173 SystemExec::SystemExec (std::string c, char **a)
174         : cmd(c) , argp(a)
175 {
176         init ();
177
178 #ifdef __WIN32__
179         make_wargs(a);
180 #endif
181         make_envp();
182 }
183
184 SystemExec::SystemExec (std::string command, const std::map<char, std::string> subs)
185 {
186         init ();
187         make_argp_escaped(command, subs);
188         cmd = argp[0];
189         // cmd = strdup(argp[0]);
190         make_envp();
191 }
192
193 void
194 SystemExec::make_argp_escaped(std::string command, const std::map<char, std::string> subs)
195 {
196
197         int inquotes = 0;
198         int n = 0;
199         size_t i = 0;
200         std::string arg = "";
201
202         argp = (char **) malloc(sizeof(char *));
203
204         for (i = 0; i <= command.length(); i++) { // include terminating '\0'
205                 char c = command.c_str()[i];
206                 if (inquotes) {
207                         if (c == '"') {
208                                 inquotes = 0;
209                         } else {
210                                 // still in quotes - just copy
211                                 arg += c;
212                         }
213                 } else switch (c) {
214                         case '%' :
215                                 c = command.c_str()[++i];
216                                 if (c == '%' || c == '\0') {
217                                         // "%%", "%" at end-of-string => "%"
218                                         arg += '%';
219                                 } else {
220                                         // search subs for string to substitute for char
221                                         std::map<char, std::string>::const_iterator s = subs.find(c);
222                                         if (s != subs.end()) {
223                                                 // found substitution
224                                                 arg += s->second;
225                                         } else {
226                                                 // not a valid substitution, just copy
227                                                 arg += '%';
228                                                 arg += c;
229                                         }
230                                 }
231                                 break;
232                         case '\\':
233                                 c = command.c_str()[++i];
234                                 switch (c) {
235                                         case ' ' :
236                                         case '"' : arg += c; break; // "\\", "\" at end-of-string => "\"
237                                         case '\0': 
238                                         case '\\': arg += '\\'; break;
239                                         default  : arg += '\\'; arg += c; break;
240                                 }
241                                 break;
242                         case '"' :
243                                 inquotes = 1;
244                                 break;
245                         case ' ' :
246                         case '\t':
247                         case '\0':
248                                 if (arg.length() > 0) {
249                                         // if there wasn't already a space or tab, start a new parameter
250                                         argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
251                                         argp[n++] = strdup (arg.c_str());
252                                         arg = "";
253                                 }
254                                 break;
255                         default :
256                                 arg += c;
257                                 break;
258                 }
259         }
260         argp[n] = NULL;
261
262         char *p = argp[0];
263         n = 0;
264         do {
265                 std::cerr << "argv[" << n << "] == \"" << p << "\"" << std::endl;
266                 p = argp[n++];
267         } while (p);
268
269 }
270
271 SystemExec::~SystemExec ()
272 {
273         terminate ();
274         if (envp) {
275                 for (int i=0;envp[i];++i) {
276                   free(envp[i]);
277                 }
278                 free (envp);
279         }
280         if (argp) {
281                 for (int i=0;argp[i];++i) {
282                   free(argp[i]);
283                 }
284                 free (argp);
285         }
286 #ifdef __WIN32__
287         if (w_args) free(w_args);
288 #endif
289         pthread_mutex_destroy(&write_lock);
290 }
291
292 void *
293 interposer_thread (void *arg) {
294         SystemExec *sex = static_cast<SystemExec *>(arg);
295         sex->output_interposer();
296         pthread_exit(0);
297         return 0;
298 }
299
300 #ifdef __WIN32__ /* Windows Process */
301
302 /* HELPER FUNCTIONS */
303
304 static void create_pipe (HANDLE *pipe, bool in) {
305         SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
306         HANDLE tmpHandle;
307         if (in) {
308                 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
309                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
310         } else {
311                 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
312                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
313         }
314         CloseHandle(tmpHandle);
315 }
316
317 static void destroy_pipe (HANDLE pipe[2]) {
318         if (pipe[0] != INVALID_HANDLE_VALUE) {
319                 CloseHandle(pipe[0]);
320                 pipe[0] = INVALID_HANDLE_VALUE;
321         }
322         if (pipe[1] != INVALID_HANDLE_VALUE) {
323                 CloseHandle(pipe[1]);
324                 pipe[1] = INVALID_HANDLE_VALUE;
325         }
326 }
327
328 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
329 {
330         DWORD currentProcId = 0;
331         GetWindowThreadProcessId(hwnd, &currentProcId);
332         if (currentProcId == (DWORD)procId)
333                 PostMessage(hwnd, WM_CLOSE, 0, 0);
334         return TRUE;
335 }
336
337 /* PROCESS API */
338
339 void
340 SystemExec::make_envp() {
341         ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
342 }
343
344 void
345 SystemExec::make_wargs(char **a) {
346         std::string wa = cmd;
347         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
348         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
349         char **tmp = a;
350         while (tmp && *tmp) {
351                 wa.append(" \"");
352                 wa.append(*tmp);
353                 wa.append("\"");
354                 tmp++;
355         }
356         w_args = strdup(wa.c_str());
357 }
358
359 void
360 SystemExec::make_argp(std::string args) {
361         std::string wa = cmd;
362         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
363         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
364         wa.append(" ");
365         wa.append(args);
366         w_args = strdup(wa.c_str());
367 }
368
369 void
370 SystemExec::terminate ()
371 {
372         ::pthread_mutex_lock(&write_lock);
373         if (pid) {
374                 /* terminate */
375                 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
376                 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
377
378                 /* kill ! */
379                 TerminateProcess(pid->hProcess, 0xf291);
380
381                 CloseHandle(pid->hThread);
382                 CloseHandle(pid->hProcess);
383                 destroy_pipe(stdinP);
384                 destroy_pipe(stdoutP);
385                 destroy_pipe(stderrP);
386                 delete pid;
387                 pid=0;
388         }
389         ::pthread_mutex_unlock(&write_lock);
390 }
391
392 int
393 SystemExec::wait (int options)
394 {
395         while (is_running()) {
396                 WaitForSingleObject(pid->hProcess, INFINITE);
397                 Sleep(20);
398         }
399         return 0;
400 }
401
402 bool
403 SystemExec::is_running ()
404 {
405         return pid?true:false;
406 }
407
408 int
409 SystemExec::start (int stderr_mode)
410 {
411         char* working_dir = 0;
412
413         if (pid) { return 0; }
414
415         pid = new PROCESS_INFORMATION;
416         memset(pid, 0, sizeof(PROCESS_INFORMATION));
417
418         create_pipe(stdinP, true);
419         create_pipe(stdoutP, false);
420
421         if (stderr_mode == 2) {
422         /* merge stout & stderr */
423                 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
424         } else if (stderr_mode == 1) {
425                 //TODO read/flush this pipe or close it...
426                 create_pipe(stderrP, false);
427         } else {
428                 //TODO: keep stderr of this process mode.
429         }
430
431         bool success = false;
432         STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
433                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
434                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
435                 0, 0, 0,
436                 STARTF_USESTDHANDLES,
437                 0, 0, 0,
438                 stdinP[0], stdoutP[1], stderrP[1]
439         };
440
441         success = CreateProcess(0, w_args,
442                 0, 0, /* bInheritHandles = */ TRUE,
443                 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
444                 /*env = */ 0,
445                 working_dir,
446                 &startupInfo, pid);
447
448         if (stdinP[0] != INVALID_HANDLE_VALUE) {
449                 CloseHandle(stdinP[0]);
450                 stdinP[0] = INVALID_HANDLE_VALUE;
451         }
452         if (stdoutP[1] != INVALID_HANDLE_VALUE) {
453                 CloseHandle(stdoutP[1]);
454                 stdoutP[1] = INVALID_HANDLE_VALUE;
455         }
456         if (stderrP[1] != INVALID_HANDLE_VALUE) {
457                 CloseHandle(stderrP[1]);
458                 stderrP[1] = INVALID_HANDLE_VALUE;
459         }
460
461         if (!success) {
462                 CloseHandle(pid->hThread);
463                 CloseHandle(pid->hProcess);
464                 destroy_pipe(stdinP);
465                 destroy_pipe(stdoutP);
466                 destroy_pipe(stderrP);
467                 delete pid;
468                 pid=0;
469                 return -1;
470         }
471
472         int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
473         thread_active=true;
474         if (rv) {
475                 thread_active=false;
476                 terminate();
477                 return -2;
478         }
479         Sleep(20);
480         return 0;
481 }
482
483 void
484 SystemExec::output_interposer()
485 {
486         DWORD bytesRead = 0;
487         char data[BUFSIZ];
488 #if 0 // untested code to set up nonblocking
489         unsigned long l = 1;
490         ioctlsocket(stdoutP[0], FIONBIO, &l);
491 #endif
492         while(1) {
493 #if 0 // for non-blocking pipes..
494                 DWORD bytesAvail = 0;
495                 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
496                 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
497 #endif
498                 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
499                 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
500                 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
501                 data[bytesRead] = 0;
502                 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
503         }
504         Terminated();/* EMIT SIGNAL */
505 }
506
507 void
508 SystemExec::close_stdin()
509 {
510         if (stdinP[0]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[0]);
511         if (stdinP[1]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[1]);
512         Sleep(200);
513         destroy_pipe(stdinP);
514 }
515
516 int
517 SystemExec::write_to_stdin(std::string d, size_t len)
518 {
519         const char *data;
520         DWORD r,c;
521
522         ::pthread_mutex_lock(&write_lock);
523
524         data=d.c_str();
525         if (len == 0) {
526                 len=(d.length());
527         }
528         c=0;
529         while (c < len) {
530                 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
531                         if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
532                                 Sleep(100);
533                                 continue;
534                         } else {
535                                 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
536                                 break;
537                         }
538                 }
539                 c += r;
540         }
541         ::pthread_mutex_unlock(&write_lock);
542         return c;
543 }
544
545
546 /* end windows process */
547 #else
548 /* UNIX/POSIX process */
549
550 extern char **environ;
551 void
552 SystemExec::make_envp() {
553         int i=0;
554         envp = (char **) calloc(1, sizeof(char*));
555         /* copy current environment */
556         for (i=0;environ[i];++i) {
557           envp[i] = strdup(environ[i]);
558           envp = (char **) realloc(envp, (i+2) * sizeof(char*));
559         }
560         envp[i] = 0;
561 }
562
563 void
564 SystemExec::make_argp(std::string args) {
565         int argn = 1;
566         char *cp1;
567         char *cp2;
568
569         char *carg = strdup(args.c_str());
570
571         argp = (char **) malloc((argn + 1) * sizeof(char *));
572         if (argp == (char **) 0) {
573                 free(carg);
574                 return; // FATAL
575         }
576
577         argp[0] = strdup(cmd.c_str());
578
579         /* TODO: quotations and escapes
580          * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
581          *
582          * It's actually not needed. All relevant invocations specify 'argp' directly.
583          * Only 'xjadeo -L -R' uses this function and that uses neither quotations
584          * nor arguments with white-space.
585          */
586         for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
587                 if (*cp2 == ' ') {
588                         *cp2 = '\0';
589                         argp[argn++] = strdup(cp1);
590                         cp1 = cp2 + 1;
591                         argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
592                 }
593         }
594         if (cp2 != cp1) {
595                 argp[argn++] = strdup(cp1);
596                 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
597         }
598         argp[argn] = (char *) 0;
599         free(carg);
600 }
601
602
603
604 void
605 SystemExec::terminate ()
606 {
607         ::pthread_mutex_lock(&write_lock);
608
609         /* close stdin in an attempt to get the child to exit cleanly.
610          */
611
612         close_stdin();
613
614         if (pid) {
615                 ::usleep(50000);
616                 sched_yield();
617                 wait(WNOHANG);
618         }
619
620         /* if pid is non-zero, the child task is still executing (i.e. it did
621          * not exit in response to stdin being closed). try to kill it.
622          */
623         
624         if (pid) {
625                 ::kill(pid, SIGTERM);
626                 ::usleep(50000);
627                 sched_yield();
628                 wait(WNOHANG);
629         }
630
631         /* if pid is non-zero, the child task is STILL executing after being
632          * sent SIGTERM. Act tough ... send SIGKILL
633          */
634
635         if (pid) {
636                 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
637                 ::kill(pid, SIGKILL);
638         }
639
640         wait();
641         if (thread_active) pthread_join(thread_id_tt, NULL);
642         thread_active = false;
643         ::pthread_mutex_unlock(&write_lock);
644 }
645
646 int
647 SystemExec::wait (int options)
648 {
649         int status=0;
650         int ret;
651
652         if (pid==0) return -1;
653
654         ret = waitpid (pid, &status, options);
655
656         if (ret == pid) {
657                 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
658                         pid=0;
659                 }
660         } else {
661                 if (ret != 0) {
662                         if (errno == ECHILD) {
663                                 /* no currently running children, reset pid */
664                                 pid=0;
665                         }
666                 } /* else the process is still running */
667         }
668         return status;
669 }
670
671 bool
672 SystemExec::is_running ()
673 {
674         int status=0;
675         if (pid==0) return false;
676         if (::waitpid(pid, &status, WNOHANG)==0) return true;
677         return false;
678 }
679
680 int
681 SystemExec::start (int stderr_mode)
682 {
683         if (is_running()) {
684                 return 0; // mmh what to return here?
685         }
686         int r;
687
688         if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
689                 /* Something unexpected went wrong creating a pipe. */
690                 return -1;
691         }
692
693         r = ::fork();
694         if (r < 0) {
695                 /* failed to fork */
696                 return -2;
697         }
698
699         if (r > 0) {
700                 /* main */
701                 pid=r;
702
703                 /* check if execve was successful. */
704                 close_fd(pok[1]);
705                 char buf;
706                 for ( ;; ) {
707                         ssize_t n = ::read(pok[0], &buf, 1 );
708                         if ( n==1 ) {
709                                 /* child process returned from execve */
710                                 pid=0;
711                                 close_fd(pok[0]);
712                                 close_fd(pin[1]);
713                                 close_fd(pin[0]);
714                                 close_fd(pout[1]);
715                                 close_fd(pout[0]);
716                                 pin[1] = -1;
717                                 return -3;
718                         } else if ( n==-1 ) {
719                                  if ( errno==EAGAIN || errno==EINTR )
720                                          continue;
721                         }
722                         break;
723                 }
724                 close_fd(pok[0]);
725                 /* child started successfully */
726
727 #if 0
728 /* use fork for output-interposer
729  * it will run in a separated process
730  */
731                 /* catch stdout thread */
732                 r = ::fork();
733                 if (r < 0) {
734                         // failed to fork
735                         terminate();
736                         return -2;
737                 }
738                 if (r == 0) {
739                         /* 2nd child process - catch stdout */
740                         close_fd(pin[1]);
741                         close_fd(pout[1]);
742                         output_interposer();
743                         exit(0);
744                 }
745                 close_fd(pout[1]);
746                 close_fd(pin[0]);
747                 close_fd(pout[0]);
748 #else /* use pthread */
749                 close_fd(pout[1]);
750                 close_fd(pin[0]);
751                 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
752
753                 thread_active=true;
754                 if (rv) {
755                         thread_active=false;
756                         terminate();
757                         return -2;
758                 }
759 #endif
760                 return 0; /* all systems go - return to main */
761         }
762
763         /* child process - exec external process */
764         close_fd(pok[0]);
765         ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
766
767         close_fd(pin[1]);
768         if (pin[0] != STDIN_FILENO) {
769           ::dup2(pin[0], STDIN_FILENO);
770         }
771         close_fd(pin[0]);
772         close_fd(pout[0]);
773         if (pout[1] != STDOUT_FILENO) {
774                 ::dup2(pout[1], STDOUT_FILENO);
775         }
776
777         if (stderr_mode == 2) {
778                 /* merge STDERR into output */
779                 if (pout[1] != STDERR_FILENO) {
780                         ::dup2(pout[1], STDERR_FILENO);
781                 }
782         } else if (stderr_mode == 1) {
783                 /* ignore STDERR */
784                 ::close(STDERR_FILENO);
785         } else {
786                 /* keep STDERR */
787         }
788
789         if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
790                 close_fd(pout[1]);
791         }
792
793         if (nicelevel !=0) {
794                 ::nice(nicelevel);
795         }
796
797 #if 0
798         /* chdir to executable dir */
799         char *directory;
800         directory = strdup(cmd.c_str());
801         if (strrchr(directory, '/') != (char *) 0) {
802                 ::chdir(directory);
803         }
804         free(directory);
805 #endif
806
807 #ifdef HAVE_SIGSET
808         sigset(SIGPIPE, SIG_DFL);
809 #else
810         signal(SIGPIPE, SIG_DFL);
811 #endif
812
813         int good_fds[1] = { -1 };
814         close_allv(good_fds);
815
816         ::execve(argp[0], argp, envp);
817         /* if we reach here something went wrong.. */
818         char buf = 0;
819         (void) ::write(pok[1], &buf, 1 );
820         close_fd(pok[1]);
821         exit(-1);
822         return -1;
823 }
824
825 void
826 SystemExec::output_interposer()
827 {
828         int rfd=pout[0];
829         char buf[BUFSIZ];
830         ssize_t r;
831         unsigned long l = 1;
832
833         ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
834
835         for (;fcntl(rfd, F_GETFL)!=-1;) {
836                 r = read(rfd, buf, sizeof(buf));
837                 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
838                         ::usleep(1000);
839                         continue;
840                 }
841                 if (r <= 0) {
842                         break;
843                 }
844                 buf[r]=0;
845                 std::string rv = std::string(buf,r); // TODO: check allocation strategy
846                 ReadStdout(rv, r);/* EMIT SIGNAL */
847         }
848         Terminated();/* EMIT SIGNAL */
849 }
850
851 void
852 SystemExec::close_stdin()
853 {
854         if (pin[1]<0) return;
855         close_fd(pin[0]);
856         close_fd(pin[1]);
857         close_fd(pout[0]);
858         close_fd(pout[1]);
859 }
860
861 int
862 SystemExec::write_to_stdin(std::string d, size_t len)
863 {
864         const char *data;
865         ssize_t r;
866         size_t c;
867         ::pthread_mutex_lock(&write_lock);
868
869         data=d.c_str();
870         if (len == 0) {
871                 len=(d.length());
872         }
873         c=0;
874         while (c < len) {
875                 for (;;) {
876                         r=::write(pin[1], data+c, len-c);
877                         if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
878                                 sleep(1);
879                                 continue;
880                         }
881                         if ((size_t) r != (len-c)) {
882                                 ::pthread_mutex_unlock(&write_lock);
883                                 return c;
884                         }
885                         break;
886                 }
887                 c += r;
888         }
889         fsync(pin[1]);
890         ::pthread_mutex_unlock(&write_lock);
891         return c;
892 }
893
894 #endif // end UNIX process