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