Merge remote-tracking branch 'origin/master' into export-dialog
[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++) {
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                                 if (arg.length() > 0) {
248                                         // if there wasn't already a space or tab, start a new parameter
249                                         argp = (char **) realloc(argp, (n + 2) * sizeof(char *));
250                                         argp[n++] = strdup (arg.c_str());
251                                         arg = "";
252                                 }
253                                 break;
254                         default :
255                                 arg += c;
256                                 break;
257                 }
258         }
259         argp[n] = NULL;
260
261         char *p = argp[0];
262         n = 0;
263         do {
264                 std::cerr << "argv[" << n << "] == \"" << p << "\"" << std::endl;
265                 p = argp[n++];
266         } while (p);
267
268 }
269
270 SystemExec::~SystemExec ()
271 {
272         terminate ();
273         if (envp) {
274                 for (int i=0;envp[i];++i) {
275                   free(envp[i]);
276                 }
277                 free (envp);
278         }
279         if (argp) {
280                 for (int i=0;argp[i];++i) {
281                   free(argp[i]);
282                 }
283                 free (argp);
284         }
285 #ifdef __WIN32__
286         if (w_args) free(w_args);
287 #endif
288         pthread_mutex_destroy(&write_lock);
289 }
290
291 void *
292 interposer_thread (void *arg) {
293         SystemExec *sex = static_cast<SystemExec *>(arg);
294         sex->output_interposer();
295         pthread_exit(0);
296         return 0;
297 }
298
299 #ifdef __WIN32__ /* Windows Process */
300
301 /* HELPER FUNCTIONS */
302
303 static void create_pipe (HANDLE *pipe, bool in) {
304         SECURITY_ATTRIBUTES secAtt = { sizeof( SECURITY_ATTRIBUTES ), NULL, TRUE };
305         HANDLE tmpHandle;
306         if (in) {
307                 if (!CreatePipe(&pipe[0], &tmpHandle, &secAtt, 1024 * 1024)) return;
308                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[1], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
309         } else {
310                 if (!CreatePipe(&tmpHandle, &pipe[1], &secAtt, 1024 * 1024)) return;
311                 if (!DuplicateHandle(GetCurrentProcess(), tmpHandle, GetCurrentProcess(), &pipe[0], 0, FALSE, DUPLICATE_SAME_ACCESS)) return;
312         }
313         CloseHandle(tmpHandle);
314 }
315
316 static void destroy_pipe (HANDLE pipe[2]) {
317         if (pipe[0] != INVALID_HANDLE_VALUE) {
318                 CloseHandle(pipe[0]);
319                 pipe[0] = INVALID_HANDLE_VALUE;
320         }
321         if (pipe[1] != INVALID_HANDLE_VALUE) {
322                 CloseHandle(pipe[1]);
323                 pipe[1] = INVALID_HANDLE_VALUE;
324         }
325 }
326
327 static BOOL CALLBACK my_terminateApp(HWND hwnd, LPARAM procId)
328 {
329         DWORD currentProcId = 0;
330         GetWindowThreadProcessId(hwnd, &currentProcId);
331         if (currentProcId == (DWORD)procId)
332                 PostMessage(hwnd, WM_CLOSE, 0, 0);
333         return TRUE;
334 }
335
336 /* PROCESS API */
337
338 void
339 SystemExec::make_envp() {
340         ;/* environemt is copied over with CreateProcess(...,env=0 ,..) */
341 }
342
343 void
344 SystemExec::make_wargs(char **a) {
345         std::string wa = cmd;
346         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
347         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
348         char **tmp = a;
349         while (tmp && *tmp) {
350                 wa.append(" \"");
351                 wa.append(*tmp);
352                 wa.append("\"");
353                 tmp++;
354         }
355         w_args = strdup(wa.c_str());
356 }
357
358 void
359 SystemExec::make_argp(std::string args) {
360         std::string wa = cmd;
361         if (cmd[0] != '"' && cmd[cmd.size()] != '"' && strchr(cmd.c_str(), ' ')) { wa = "\"" + cmd + "\""; }
362         std::replace(cmd.begin(), cmd.end(), '/', '\\' );
363         wa.append(" ");
364         wa.append(args);
365         w_args = strdup(wa.c_str());
366 }
367
368 void
369 SystemExec::terminate ()
370 {
371         ::pthread_mutex_lock(&write_lock);
372         if (pid) {
373                 /* terminate */
374                 EnumWindows(my_terminateApp, (LPARAM)pid->dwProcessId);
375                 PostThreadMessage(pid->dwThreadId, WM_CLOSE, 0, 0);
376
377                 /* kill ! */
378                 TerminateProcess(pid->hProcess, 0xf291);
379
380                 CloseHandle(pid->hThread);
381                 CloseHandle(pid->hProcess);
382                 destroy_pipe(stdinP);
383                 destroy_pipe(stdoutP);
384                 destroy_pipe(stderrP);
385                 delete pid;
386                 pid=0;
387         }
388         ::pthread_mutex_unlock(&write_lock);
389 }
390
391 int
392 SystemExec::wait (int options)
393 {
394         while (is_running()) {
395                 WaitForSingleObject(pid->hProcess, INFINITE);
396                 Sleep(20);
397         }
398         return 0;
399 }
400
401 bool
402 SystemExec::is_running ()
403 {
404         return pid?true:false;
405 }
406
407 int
408 SystemExec::start (int stderr_mode)
409 {
410         char* working_dir = 0;
411
412         if (pid) { return 0; }
413
414         pid = new PROCESS_INFORMATION;
415         memset(pid, 0, sizeof(PROCESS_INFORMATION));
416
417         create_pipe(stdinP, true);
418         create_pipe(stdoutP, false);
419
420         if (stderr_mode == 2) {
421         /* merge stout & stderr */
422                 DuplicateHandle(GetCurrentProcess(), stdoutP[1], GetCurrentProcess(), &stderrP[1], 0, TRUE, DUPLICATE_SAME_ACCESS);
423         } else if (stderr_mode == 1) {
424                 //TODO read/flush this pipe or close it...
425                 create_pipe(stderrP, false);
426         } else {
427                 //TODO: keep stderr of this process mode.
428         }
429
430         bool success = false;
431         STARTUPINFOA startupInfo = { sizeof( STARTUPINFO ), 0, 0, 0,
432                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
433                 (unsigned long)CW_USEDEFAULT, (unsigned long)CW_USEDEFAULT,
434                 0, 0, 0,
435                 STARTF_USESTDHANDLES,
436                 0, 0, 0,
437                 stdinP[0], stdoutP[1], stderrP[1]
438         };
439
440         success = CreateProcess(0, w_args,
441                 0, 0, /* bInheritHandles = */ TRUE,
442                 (CREATE_NO_WINDOW&0) | CREATE_UNICODE_ENVIRONMENT | (0&CREATE_NEW_CONSOLE),
443                 /*env = */ 0,
444                 working_dir,
445                 &startupInfo, pid);
446
447         if (stdinP[0] != INVALID_HANDLE_VALUE) {
448                 CloseHandle(stdinP[0]);
449                 stdinP[0] = INVALID_HANDLE_VALUE;
450         }
451         if (stdoutP[1] != INVALID_HANDLE_VALUE) {
452                 CloseHandle(stdoutP[1]);
453                 stdoutP[1] = INVALID_HANDLE_VALUE;
454         }
455         if (stderrP[1] != INVALID_HANDLE_VALUE) {
456                 CloseHandle(stderrP[1]);
457                 stderrP[1] = INVALID_HANDLE_VALUE;
458         }
459
460         if (!success) {
461                 CloseHandle(pid->hThread);
462                 CloseHandle(pid->hProcess);
463                 destroy_pipe(stdinP);
464                 destroy_pipe(stdoutP);
465                 destroy_pipe(stderrP);
466                 delete pid;
467                 pid=0;
468                 return -1;
469         }
470
471         int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
472         thread_active=true;
473         if (rv) {
474                 thread_active=false;
475                 terminate();
476                 return -2;
477         }
478         Sleep(20);
479         return 0;
480 }
481
482 void
483 SystemExec::output_interposer()
484 {
485         DWORD bytesRead = 0;
486         char data[BUFSIZ];
487 #if 0 // untested code to set up nonblocking
488         unsigned long l = 1;
489         ioctlsocket(stdoutP[0], FIONBIO, &l);
490 #endif
491         while(1) {
492 #if 0 // for non-blocking pipes..
493                 DWORD bytesAvail = 0;
494                 PeekNamedPipe(stdoutP[0], 0, 0, 0, &bytesAvail, 0);
495                 if (bytesAvail < 1) {Sleep(500); printf("N/A\n"); continue;}
496 #endif
497                 if (stdoutP[0] == INVALID_HANDLE_VALUE) break;
498                 if (!ReadFile(stdoutP[0], data, BUFSIZ, &bytesRead, 0)) break;
499                 if (bytesRead < 1) continue; /* actually not needed; but this is safe. */
500                 data[bytesRead] = 0;
501                 ReadStdout(data, bytesRead);/* EMIT SIGNAL */
502         }
503         Terminated();/* EMIT SIGNAL */
504 }
505
506 void
507 SystemExec::close_stdin()
508 {
509         if (stdinP[0]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[0]);
510         if (stdinP[1]!= INVALID_HANDLE_VALUE)  FlushFileBuffers(stdinP[1]);
511         Sleep(200);
512         destroy_pipe(stdinP);
513 }
514
515 int
516 SystemExec::write_to_stdin(std::string d, size_t len)
517 {
518         const char *data;
519         DWORD r,c;
520
521         ::pthread_mutex_lock(&write_lock);
522
523         data=d.c_str();
524         if (len == 0) {
525                 len=(d.length());
526         }
527         c=0;
528         while (c < len) {
529                 if (!WriteFile(stdinP[1], data+c, len-c, &r, NULL)) {
530                         if (GetLastError() == 0xE8 /*NT_STATUS_INVALID_USER_BUFFER*/) {
531                                 Sleep(100);
532                                 continue;
533                         } else {
534                                 fprintf(stderr, "SYSTEM-EXEC: stdin write error.\n");
535                                 break;
536                         }
537                 }
538                 c += r;
539         }
540         ::pthread_mutex_unlock(&write_lock);
541         return c;
542 }
543
544
545 /* end windows process */
546 #else
547 /* UNIX/POSIX process */
548
549 extern char **environ;
550 void
551 SystemExec::make_envp() {
552         int i=0;
553         envp = (char **) calloc(1, sizeof(char*));
554         /* copy current environment */
555         for (i=0;environ[i];++i) {
556           envp[i] = strdup(environ[i]);
557           envp = (char **) realloc(envp, (i+2) * sizeof(char*));
558         }
559         envp[i] = 0;
560 }
561
562 void
563 SystemExec::make_argp(std::string args) {
564         int argn = 1;
565         char *cp1;
566         char *cp2;
567
568         char *carg = strdup(args.c_str());
569
570         argp = (char **) malloc((argn + 1) * sizeof(char *));
571         if (argp == (char **) 0) {
572                 free(carg);
573                 return; // FATAL
574         }
575
576         argp[0] = strdup(cmd.c_str());
577
578         /* TODO: quotations and escapes
579          * http://stackoverflow.com/questions/1511797/convert-string-to-argv-in-c
580          *
581          * It's actually not needed. All relevant invocations specify 'argp' directly.
582          * Only 'xjadeo -L -R' uses this function and that uses neither quotations
583          * nor arguments with white-space.
584          */
585         for (cp1 = cp2 = carg; *cp2 != '\0'; ++cp2) {
586                 if (*cp2 == ' ') {
587                         *cp2 = '\0';
588                         argp[argn++] = strdup(cp1);
589                         cp1 = cp2 + 1;
590                         argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
591                 }
592         }
593         if (cp2 != cp1) {
594                 argp[argn++] = strdup(cp1);
595                 argp = (char **) realloc(argp, (argn + 1) * sizeof(char *));
596         }
597         argp[argn] = (char *) 0;
598         free(carg);
599 }
600
601
602
603 void
604 SystemExec::terminate ()
605 {
606         ::pthread_mutex_lock(&write_lock);
607
608         /* close stdin in an attempt to get the child to exit cleanly.
609          */
610
611         close_stdin();
612
613         if (pid) {
614                 ::usleep(50000);
615                 sched_yield();
616                 wait(WNOHANG);
617         }
618
619         /* if pid is non-zero, the child task is still executing (i.e. it did
620          * not exit in response to stdin being closed). try to kill it.
621          */
622         
623         if (pid) {
624                 ::kill(pid, SIGTERM);
625                 ::usleep(50000);
626                 sched_yield();
627                 wait(WNOHANG);
628         }
629
630         /* if pid is non-zero, the child task is STILL executing after being
631          * sent SIGTERM. Act tough ... send SIGKILL
632          */
633
634         if (pid) {
635                 ::fprintf(stderr, "Process is still running! trying SIGKILL\n");
636                 ::kill(pid, SIGKILL);
637         }
638
639         wait();
640         if (thread_active) pthread_join(thread_id_tt, NULL);
641         thread_active = false;
642         ::pthread_mutex_unlock(&write_lock);
643 }
644
645 int
646 SystemExec::wait (int options)
647 {
648         int status=0;
649         int ret;
650
651         if (pid==0) return -1;
652
653         ret = waitpid (pid, &status, options);
654
655         if (ret == pid) {
656                 if (WEXITSTATUS(status) || WIFSIGNALED(status)) {
657                         pid=0;
658                 }
659         } else {
660                 if (ret != 0) {
661                         if (errno == ECHILD) {
662                                 /* no currently running children, reset pid */
663                                 pid=0;
664                         }
665                 } /* else the process is still running */
666         }
667         return status;
668 }
669
670 bool
671 SystemExec::is_running ()
672 {
673         int status=0;
674         if (pid==0) return false;
675         if (::waitpid(pid, &status, WNOHANG)==0) return true;
676         return false;
677 }
678
679 int
680 SystemExec::start (int stderr_mode)
681 {
682         if (is_running()) {
683                 return 0; // mmh what to return here?
684         }
685         int r;
686
687         if (::pipe(pin) < 0 || ::pipe(pout) < 0 || ::pipe(pok) < 0) {
688                 /* Something unexpected went wrong creating a pipe. */
689                 return -1;
690         }
691
692         r = ::fork();
693         if (r < 0) {
694                 /* failed to fork */
695                 return -2;
696         }
697
698         if (r > 0) {
699                 /* main */
700                 pid=r;
701
702                 /* check if execve was successful. */
703                 close_fd(pok[1]);
704                 char buf;
705                 for ( ;; ) {
706                         ssize_t n = ::read(pok[0], &buf, 1 );
707                         if ( n==1 ) {
708                                 /* child process returned from execve */
709                                 pid=0;
710                                 close_fd(pok[0]);
711                                 close_fd(pin[1]);
712                                 close_fd(pin[0]);
713                                 close_fd(pout[1]);
714                                 close_fd(pout[0]);
715                                 pin[1] = -1;
716                                 return -3;
717                         } else if ( n==-1 ) {
718                                  if ( errno==EAGAIN || errno==EINTR )
719                                          continue;
720                         }
721                         break;
722                 }
723                 close_fd(pok[0]);
724                 /* child started successfully */
725
726 #if 0
727 /* use fork for output-interposer
728  * it will run in a separated process
729  */
730                 /* catch stdout thread */
731                 r = ::fork();
732                 if (r < 0) {
733                         // failed to fork
734                         terminate();
735                         return -2;
736                 }
737                 if (r == 0) {
738                         /* 2nd child process - catch stdout */
739                         close_fd(pin[1]);
740                         close_fd(pout[1]);
741                         output_interposer();
742                         exit(0);
743                 }
744                 close_fd(pout[1]);
745                 close_fd(pin[0]);
746                 close_fd(pout[0]);
747 #else /* use pthread */
748                 close_fd(pout[1]);
749                 close_fd(pin[0]);
750                 int rv = pthread_create(&thread_id_tt, NULL, interposer_thread, this);
751
752                 thread_active=true;
753                 if (rv) {
754                         thread_active=false;
755                         terminate();
756                         return -2;
757                 }
758 #endif
759                 return 0; /* all systems go - return to main */
760         }
761
762         /* child process - exec external process */
763         close_fd(pok[0]);
764         ::fcntl(pok[1], F_SETFD, FD_CLOEXEC);
765
766         close_fd(pin[1]);
767         if (pin[0] != STDIN_FILENO) {
768           ::dup2(pin[0], STDIN_FILENO);
769         }
770         close_fd(pin[0]);
771         close_fd(pout[0]);
772         if (pout[1] != STDOUT_FILENO) {
773                 ::dup2(pout[1], STDOUT_FILENO);
774         }
775
776         if (stderr_mode == 2) {
777                 /* merge STDERR into output */
778                 if (pout[1] != STDERR_FILENO) {
779                         ::dup2(pout[1], STDERR_FILENO);
780                 }
781         } else if (stderr_mode == 1) {
782                 /* ignore STDERR */
783                 ::close(STDERR_FILENO);
784         } else {
785                 /* keep STDERR */
786         }
787
788         if (pout[1] != STDOUT_FILENO && pout[1] != STDERR_FILENO) {
789                 close_fd(pout[1]);
790         }
791
792         if (nicelevel !=0) {
793                 ::nice(nicelevel);
794         }
795
796 #if 0
797         /* chdir to executable dir */
798         char *directory;
799         directory = strdup(cmd.c_str());
800         if (strrchr(directory, '/') != (char *) 0) {
801                 ::chdir(directory);
802         }
803         free(directory);
804 #endif
805
806 #ifdef HAVE_SIGSET
807         sigset(SIGPIPE, SIG_DFL);
808 #else
809         signal(SIGPIPE, SIG_DFL);
810 #endif
811
812         int good_fds[1] = { -1 };
813         close_allv(good_fds);
814
815         ::execve(argp[0], argp, envp);
816         /* if we reach here something went wrong.. */
817         char buf = 0;
818         (void) ::write(pok[1], &buf, 1 );
819         close_fd(pok[1]);
820         exit(-1);
821         return -1;
822 }
823
824 void
825 SystemExec::output_interposer()
826 {
827         int rfd=pout[0];
828         char buf[BUFSIZ];
829         ssize_t r;
830         unsigned long l = 1;
831
832         ioctl(rfd, FIONBIO, &l); // set non-blocking I/O
833
834         for (;fcntl(rfd, F_GETFL)!=-1;) {
835                 r = read(rfd, buf, sizeof(buf));
836                 if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
837                         ::usleep(1000);
838                         continue;
839                 }
840                 if (r <= 0) {
841                         break;
842                 }
843                 buf[r]=0;
844                 std::string rv = std::string(buf,r); // TODO: check allocation strategy
845                 ReadStdout(rv, r);/* EMIT SIGNAL */
846         }
847         Terminated();/* EMIT SIGNAL */
848 }
849
850 void
851 SystemExec::close_stdin()
852 {
853         if (pin[1]<0) return;
854         close_fd(pin[0]);
855         close_fd(pin[1]);
856         close_fd(pout[0]);
857         close_fd(pout[1]);
858 }
859
860 int
861 SystemExec::write_to_stdin(std::string d, size_t len)
862 {
863         const char *data;
864         ssize_t r;
865         size_t c;
866         ::pthread_mutex_lock(&write_lock);
867
868         data=d.c_str();
869         if (len == 0) {
870                 len=(d.length());
871         }
872         c=0;
873         while (c < len) {
874                 for (;;) {
875                         r=::write(pin[1], data+c, len-c);
876                         if (r < 0 && (errno == EINTR || errno == EAGAIN)) {
877                                 sleep(1);
878                                 continue;
879                         }
880                         if ((size_t) r != (len-c)) {
881                                 ::pthread_mutex_unlock(&write_lock);
882                                 return c;
883                         }
884                         break;
885                 }
886                 c += r;
887         }
888         fsync(pin[1]);
889         ::pthread_mutex_unlock(&write_lock);
890         return c;
891 }
892
893 #endif // end UNIX process