2 This file is part of GNUnet
3 (C) 2002, 2003, 2004, 2005, 2006, 2011 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file util/os_priority.c
23 * @brief Methods to set process priority
28 #include "gnunet_common.h"
29 #include "gnunet_os_lib.h"
30 #include "gnunet_scheduler_lib.h"
31 #include "gnunet_strings_lib.h"
32 #include "gnunet_crypto_lib.h"
36 #define LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
38 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
40 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
42 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
45 struct GNUNET_OS_Process
60 * Pipe we use to signal the process (if used).
62 struct GNUNET_DISK_FileHandle *control_pipe;
65 * Name of the pipe, NULL for none.
72 * Handle for 'this' process.
74 static struct GNUNET_OS_Process current_process;
77 /* MinGW version of named pipe API */
80 * Creates a named pipe/FIFO and opens it
82 * @param fn pointer to the name of the named pipe or to NULL,
83 * possibly updated to the new name (or free'd)
84 * @param flags open flags
85 * @param perm access permissions
86 * @return pipe handle on success, NULL on error
88 static struct GNUNET_DISK_FileHandle *
89 npipe_create (char **fn, enum GNUNET_DISK_OpenFlags flags,
90 enum GNUNET_DISK_AccessPermissions perm)
92 struct GNUNET_DISK_FileHandle *ret;
98 if (flags & GNUNET_DISK_OPEN_READWRITE)
99 openMode = PIPE_ACCESS_DUPLEX;
100 else if (flags & GNUNET_DISK_OPEN_READ)
101 openMode = PIPE_ACCESS_INBOUND;
102 else if (flags & GNUNET_DISK_OPEN_WRITE)
103 openMode = PIPE_ACCESS_OUTBOUND;
104 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
105 openMode |= FILE_FLAG_FIRST_PIPE_INSTANCE;
114 GNUNET_asprintf (&name, "\\\\.\\pipe\\%.246s", fn);
115 LOG (GNUNET_ERROR_TYPE_DEBUG,
116 "Trying to create an instance of named pipe `%s'\n", name);
117 /* 1) This might work just fine with UTF-8 strings as it is.
118 * 2) This is only used by GNUnet itself, and only with latin names.
120 h = CreateNamedPipe (name, openMode | FILE_FLAG_OVERLAPPED,
121 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 2, 1, 1, 0,
126 GNUNET_asprintf (fn, "\\\\.\\pipe\\gnunet-%llu",
127 GNUNET_CRYPTO_random_u64 (GNUNET_CRYPTO_QUALITY_WEAK,
129 LOG (GNUNET_ERROR_TYPE_DEBUG, "Trying to create unique named pipe `%s'\n",
131 h = CreateNamedPipe (*fn,
132 openMode | FILE_FLAG_OVERLAPPED |
133 FILE_FLAG_FIRST_PIPE_INSTANCE,
134 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 2, 1, 1, 0,
137 error_code = GetLastError ();
138 GNUNET_free_non_null (name);
139 /* don't re-set name to NULL yet */
140 if (INVALID_HANDLE_VALUE == h)
142 SetErrnoFromWinError (error_code);
143 LOG (GNUNET_ERROR_TYPE_DEBUG,
144 "Pipe creation have failed because of %d, errno is %d\n", error_code,
148 LOG (GNUNET_ERROR_TYPE_DEBUG,
149 "Pipe was to be unique, considering re-creation\n");
152 if ( (ERROR_ACCESS_DENIED != error_code) && (ERROR_PIPE_BUSY != error_code) )
154 LOG (GNUNET_ERROR_TYPE_DEBUG,
155 "Pipe name was not unique, trying again\n");
162 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
164 ret->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
165 ret->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
166 ret->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
167 ret->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
168 ret->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
174 * Opens already existing named pipe/FIFO
176 * @param fn name of an existing named pipe
177 * @param flags open flags
178 * @return pipe handle on success, NULL on error
180 static struct GNUNET_DISK_FileHandle *
181 npipe_open (const char *fn, enum GNUNET_DISK_OpenFlags flags)
183 struct GNUNET_DISK_FileHandle *ret;
188 if (flags & GNUNET_DISK_OPEN_READWRITE)
189 openMode = GENERIC_WRITE | GENERIC_READ;
190 else if (flags & GNUNET_DISK_OPEN_READ)
191 openMode = GENERIC_READ;
192 else if (flags & GNUNET_DISK_OPEN_WRITE)
193 openMode = GENERIC_WRITE;
195 h = CreateFile (fn, openMode, 0, NULL, OPEN_EXISTING,
196 FILE_FLAG_OVERLAPPED | FILE_READ_ATTRIBUTES, NULL);
197 if (INVALID_HANDLE_VALUE == h)
199 SetErrnoFromWinError (GetLastError ());
203 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
205 ret->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
206 ret->oOverlapRead = GNUNET_malloc (sizeof (OVERLAPPED));
207 ret->oOverlapWrite = GNUNET_malloc (sizeof (OVERLAPPED));
208 ret->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
209 ret->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
215 /* UNIX version of named-pipe API */
218 * Clean up a named pipe and the directory it was placed in.
220 * @param fn name of the pipe
223 cleanup_npipe (const char *fn)
228 if (0 != unlink (fn))
229 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "unlink", fn);
230 dn = GNUNET_strdup (fn);
233 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "rmdir", dp);
239 * Setup a named pipe.
241 * @param fn where to store the name of the new pipe,
242 * if *fn is non-null, the name of the pipe to setup
243 * @return GNUNET_OK on success
246 npipe_setup (char **fn)
250 /* FIXME: hardwired '/tmp' path... is bad */
251 char dir[] = "/tmp/gnunet-pipe-XXXXXX";
253 if (NULL == mkdtemp (dir))
255 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "mkdtemp");
256 return GNUNET_SYSERR;
258 GNUNET_asprintf (fn, "%s/child-control", dir);
260 if (-1 == mkfifo (*fn, S_IRUSR | S_IWUSR))
261 return GNUNET_SYSERR;
267 * Open an existing named pipe.
269 * @param fn name of the file
270 * @param flags flags to use
271 * @return NULL on error
273 static struct GNUNET_DISK_FileHandle *
274 npipe_open (const char *fn,
275 enum GNUNET_DISK_OpenFlags flags)
277 struct GNUNET_DISK_FileHandle *ret;
282 /* 200 * 5ms = 1s at most */
285 fd = open (fn, O_NONBLOCK | ((flags == GNUNET_DISK_OPEN_READ) ? O_RDONLY : O_WRONLY));
286 if ( (-1 != fd) || (9 == i) || (flags == GNUNET_DISK_OPEN_READ))
288 /* as this is for killing a child process via pipe and it is conceivable that
289 the child process simply didn't finish starting yet, we do some sleeping
290 (which is obviously usually not allowed). We can't select on the FD as
291 'open' fails, and we probably shouldn't just "ignore" the error, so wait
292 and retry a few times is likely the best method; our process API doesn't
293 support continuations, so we need to sleep directly... */
295 req.tv_nsec = 5000000; /* 5ms */
296 (void) nanosleep (&req, NULL);
300 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
301 (flags == GNUNET_DISK_OPEN_READ)
302 ? _("Failed to open named pipe `%s' for reading: %s\n")
303 : _("Failed to open named pipe `%s' for writing: %s\n"),
308 ret = GNUNET_malloc (sizeof (struct GNUNET_DISK_FileHandle));
316 * This handler is called when there are control data to be read on the pipe
318 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
319 * @param tc scheduler context
322 parent_control_handler (void *cls,
323 const struct GNUNET_SCHEDULER_TaskContext *tc)
325 struct GNUNET_DISK_FileHandle *control_pipe = cls;
329 LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
331 if (0 != (tc->reason &
332 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT)))
334 GNUNET_DISK_file_close (control_pipe);
338 ret = GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig));
339 if (sizeof (sig) != ret)
342 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
343 GNUNET_DISK_file_close (control_pipe);
347 LOG (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
348 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
349 control_pipe, &parent_control_handler,
356 * Task that connects this process to its parent via pipe;
357 * essentially, the parent control handler will read signal numbers
358 * from the 'GNUNET_OS_CONTROL_PIPE' (as given in an environment
359 * variable) and raise those signals.
361 * @param cls closure (unused)
362 * @param tc scheduler context (unused)
365 GNUNET_OS_install_parent_control_handler (void *cls,
367 GNUNET_SCHEDULER_TaskContext *tc)
370 struct GNUNET_DISK_FileHandle *control_pipe;
372 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
373 if ( (NULL == env_buf) || (strlen (env_buf) <= 0) )
375 LOG (GNUNET_ERROR_TYPE_DEBUG,
376 "Not installing a handler because $%s is empty\n",
377 GNUNET_OS_CONTROL_PIPE);
378 putenv ("GNUNET_OS_CONTROL_PIPE=");
382 npipe_open (env_buf, GNUNET_DISK_OPEN_READ);
383 if (NULL == control_pipe)
385 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
386 putenv ("GNUNET_OS_CONTROL_PIPE=");
389 LOG (GNUNET_ERROR_TYPE_DEBUG,
390 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
391 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
392 &parent_control_handler, control_pipe);
393 putenv ("GNUNET_OS_CONTROL_PIPE=");
398 * Get process structure for current process
400 * The pointer it returns points to static memory location and must not be
403 * @return pointer to the process sturcutre for this process
405 struct GNUNET_OS_Process *
406 GNUNET_OS_process_current ()
409 current_process.pid = GetCurrentProcessId ();
410 current_process.handle = GetCurrentProcess ();
412 current_process.pid = 0;
414 return ¤t_process;
419 * Sends a signal to the process
421 * @param proc pointer to process structure
423 * @return 0 on success, -1 on error
426 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
433 if ( (NULL == proc->control_pipe) &&
434 (NULL != proc->childpipename) )
435 proc->control_pipe = npipe_open (proc->childpipename,
436 GNUNET_DISK_OPEN_WRITE);
438 if (NULL != proc->control_pipe)
440 ret = GNUNET_DISK_file_write (proc->control_pipe, &csig, sizeof (csig));
441 if (sizeof (csig) == ret)
444 /* pipe failed or non-existent, try other methods */
453 #if WINDOWS && !defined(__CYGWIN__)
456 int must_kill = GNUNET_YES;
457 if (0 != GetExitCodeProcess (proc->handle, &exitcode))
458 must_kill = (exitcode == STILL_ACTIVE) ? GNUNET_YES : GNUNET_NO;
459 if (GNUNET_YES == must_kill)
460 if (0 == SafeTerminateProcess (proc->handle, 0, 0))
462 DWORD error_code = GetLastError ();
463 if ((error_code != WAIT_TIMEOUT) && (error_code != ERROR_PROCESS_ABORTED))
465 LOG ((error_code == ERROR_ACCESS_DENIED) ?
466 GNUNET_ERROR_TYPE_INFO : GNUNET_ERROR_TYPE_WARNING,
467 "SafeTermiateProcess failed with code %lu\n", error_code);
468 /* The problem here is that a process that is already dying
469 * might cause SafeTerminateProcess to fail with
470 * ERROR_ACCESS_DENIED, but the process WILL die eventually.
471 * If we really had a permissions problem, hanging up (which
472 * is what will happen in process_wait() in that case) is
475 if (ERROR_ACCESS_DENIED == error_code)
481 SetErrnoFromWinError (error_code);
489 return PLIBC_KILL (proc->pid, sig);
496 return PLIBC_KILL (proc->pid, sig);
502 * Get the pid of the process in question
504 * @param proc the process to get the pid of
506 * @return the current process id
509 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
516 * Cleans up process structure contents (OS-dependent) and deallocates it
518 * @param proc pointer to process structure
521 GNUNET_OS_process_destroy (struct GNUNET_OS_Process *proc)
523 if (NULL != proc->control_pipe)
524 GNUNET_DISK_file_close (proc->control_pipe);
527 if (proc->handle != NULL)
528 CloseHandle (proc->handle);
530 if (NULL != proc->childpipename)
533 cleanup_npipe (proc->childpipename);
535 GNUNET_free (proc->childpipename);
542 #include "gnunet_signal_lib.h"
544 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
547 * Make seaspider happy.
549 #define DWORD_WINAPI DWORD WINAPI
552 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
553 * @param proc pointer to process structure
556 child_wait_thread (void *arg)
558 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
560 WaitForSingleObject (proc->handle, INFINITE);
562 if (w32_sigchld_handler)
563 w32_sigchld_handler ();
571 * Set process priority
573 * @param proc pointer to process structure
574 * @param prio priority value
575 * @return GNUNET_OK on success, GNUNET_SYSERR on error
578 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
579 enum GNUNET_SCHEDULER_Priority prio)
583 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
584 if (GNUNET_SCHEDULER_PRIORITY_KEEP == prio)
587 /* convert to MINGW/Unix values */
590 case GNUNET_SCHEDULER_PRIORITY_UI:
591 case GNUNET_SCHEDULER_PRIORITY_URGENT:
593 rprio = HIGH_PRIORITY_CLASS;
599 case GNUNET_SCHEDULER_PRIORITY_HIGH:
601 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
607 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
609 rprio = NORMAL_PRIORITY_CLASS;
615 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
617 rprio = BELOW_NORMAL_PRIORITY_CLASS;
623 case GNUNET_SCHEDULER_PRIORITY_IDLE:
625 rprio = IDLE_PRIORITY_CLASS;
632 return GNUNET_SYSERR;
635 /* Set process priority */
638 HANDLE h = proc->handle;
640 GNUNET_assert (h != NULL);
641 SetPriorityClass (h, rprio);
647 if ((0 == pid) || (pid == getpid ()))
650 int delta = rprio - have;
653 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
655 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
656 return GNUNET_SYSERR;
661 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
663 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
665 return GNUNET_SYSERR;
669 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
670 "Priority management not availabe for this platform\n");
678 CreateCustomEnvTable (char **vars)
680 char *win32_env_table;
685 size_t tablesize = 0;
686 size_t items_count = 0;
695 win32_env_table = GetEnvironmentStringsA ();
696 if (NULL == win32_env_table)
698 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
700 index = GNUNET_malloc (sizeof (char *) * n_var);
701 for (c = 0; c < n_var; c++)
703 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
705 size_t len = strlen (ptr);
708 for (var_ptr = vars; *var_ptr; var_ptr++)
712 var_len = strlen (var);
713 if (strncmp (var, ptr, var_len) == 0)
717 tablesize += var_len + strlen (val) + 1;
722 tablesize += len + 1;
725 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
730 n_found += strlen (var) + strlen (val) + 1;
732 result = GNUNET_malloc (tablesize + n_found + 1);
733 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
735 size_t len = strlen (ptr);
738 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
742 var_len = strlen (var);
743 if (strncmp (var, ptr, var_len) == 0)
751 strcpy (result_ptr, ptr);
752 result_ptr += len + 1;
756 strcpy (result_ptr, var);
757 result_ptr += var_len;
758 strcpy (result_ptr, val);
759 result_ptr += strlen (val) + 1;
763 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
767 var_len = strlen (var);
770 strcpy (result_ptr, var);
771 result_ptr += var_len;
772 strcpy (result_ptr, val);
773 result_ptr += strlen (val) + 1;
776 FreeEnvironmentStrings (win32_env_table);
785 * Open '/dev/null' and make the result the given
788 * @param target_fd desired FD to point to /dev/null
789 * @param flags open flags (O_RDONLY, O_WRONLY)
792 open_dev_null (int target_fd,
797 fd = open ("/dev/null", flags);
800 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", "/dev/null");
805 if (-1 == dup2 (fd, target_fd))
807 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
811 GNUNET_break (0 == close (fd));
819 * @param pipe_control should a pipe be used to send signals to the child?
820 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
821 * std handles of the parent are inherited by the child.
822 * pipe_stdin and pipe_stdout take priority over std_inheritance
823 * (when they are non-NULL).
824 * @param pipe_stdin pipe to use to send input to child process (or NULL)
825 * @param pipe_stdout pipe to use to get output from child process (or NULL)
826 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
827 * must be NULL on platforms where dup is not supported
828 * @param filename name of the binary
829 * @param argv NULL-terminated list of arguments to the process
830 * @return process ID of the new process, -1 on error
832 static struct GNUNET_OS_Process *
833 start_process (int pipe_control,
834 enum GNUNET_OS_InheritStdioFlags std_inheritance,
835 struct GNUNET_DISK_PipeHandle *pipe_stdin,
836 struct GNUNET_DISK_PipeHandle *pipe_stdout,
837 const SOCKTYPE *lsocks,
838 const char *filename,
845 struct GNUNET_OS_Process *gnunet_proc;
846 char *childpipename = NULL;
859 if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename))
860 return NULL; /* not executable */
861 if ( (GNUNET_YES == pipe_control) &&
862 (GNUNET_OK != npipe_setup (&childpipename)) )
864 if (NULL != pipe_stdout)
866 GNUNET_assert (GNUNET_OK ==
867 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
869 GNUNET_DISK_PIPE_END_WRITE),
870 &fd_stdout_write, sizeof (int)));
871 GNUNET_assert (GNUNET_OK ==
872 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
873 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
874 &fd_stdout_read, sizeof (int)));
876 if (NULL != pipe_stdin)
878 GNUNET_assert (GNUNET_OK ==
879 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
880 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
881 &fd_stdin_read, sizeof (int)));
882 GNUNET_assert (GNUNET_OK ==
883 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
884 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
885 &fd_stdin_write, sizeof (int)));
892 while (-1 != (k = lsocks[i++]))
893 GNUNET_array_append (lscp, ls, k);
894 GNUNET_array_append (lscp, ls, -1);
901 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
902 GNUNET_free_non_null (childpipename);
903 GNUNET_array_grow (lscp, ls, 0);
909 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
910 gnunet_proc->pid = ret;
911 gnunet_proc->childpipename = childpipename;
912 GNUNET_array_grow (lscp, ls, 0);
915 if (NULL != childpipename)
917 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
918 GNUNET_free (childpipename);
920 if (NULL != pipe_stdin)
922 GNUNET_break (0 == close (fd_stdin_write));
923 if (-1 == dup2 (fd_stdin_read, 0))
924 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
925 GNUNET_break (0 == close (fd_stdin_read));
927 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_IN))
929 GNUNET_break (0 == close (0));
930 open_dev_null (0, O_RDONLY);
932 if (NULL != pipe_stdout)
934 GNUNET_break (0 == close (fd_stdout_read));
935 if (-1 == dup2 (fd_stdout_write, 1))
936 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
937 GNUNET_break (0 == close (fd_stdout_write));
939 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_OUT))
941 GNUNET_break (0 == close (1));
942 open_dev_null (1, O_WRONLY);
944 if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_ERR))
946 GNUNET_break (0 == close (2));
947 open_dev_null (2, O_WRONLY);
951 /* read systemd documentation... */
952 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
953 setenv ("LISTEN_PID", lpid, 1);
956 while (-1 != lscp[i])
959 while (-1 != lscp[j])
965 GNUNET_assert (-1 != k);
966 GNUNET_assert (0 == close (lscp[j]));
974 /* Bury any existing FD, no matter what; they should all be closed
975 * on exec anyway and the important onces have been dup'ed away */
977 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
979 /* unset close-on-exec flag */
980 flags = fcntl (tgt, F_GETFD);
981 GNUNET_assert (flags >= 0);
982 flags &= ~FD_CLOEXEC;
984 (void) fcntl (tgt, F_SETFD, flags);
988 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
989 setenv ("LISTEN_FDS", fds, 1);
991 GNUNET_array_grow (lscp, ls, 0);
992 execvp (filename, argv);
993 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
996 struct GNUNET_DISK_FileHandle *control_pipe;
997 char *childpipename = NULL;
999 char **non_const_argv;
1000 unsigned int cmdlen;
1004 PROCESS_INFORMATION proc;
1006 struct GNUNET_OS_Process *gnunet_proc;
1007 char path[MAX_PATH + 1];
1008 char *our_env[5] = { NULL, NULL, NULL, NULL, NULL };
1009 char *env_block = NULL;
1017 char *non_const_filename;
1018 char win_path[MAX_PATH + 1];
1019 struct GNUNET_DISK_PipeHandle *lsocks_pipe;
1020 const struct GNUNET_DISK_FileHandle *lsocks_write_fd;
1022 HANDLE lsocks_write;
1030 HANDLE stdin_handle;
1031 HANDLE stdout_handle;
1032 HANDLE stdih, stdoh, stdeh;
1033 DWORD stdif, stdof, stdef;
1037 if (GNUNET_SYSERR == GNUNET_OS_check_helper_binary (filename))
1038 return NULL; /* not executable */
1040 /* Search in prefix dir (hopefully - the directory from which
1041 * the current module was loaded), bindir and libdir, then in PATH
1043 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1044 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1045 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1047 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1050 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1053 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1056 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1057 GNUNET_free (self_prefix);
1058 GNUNET_free (bindir);
1059 GNUNET_free (libdir);
1061 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1062 if (alloc_len != pathbuf_len - 1)
1064 GNUNET_free (pathbuf);
1065 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1069 cmdlen = strlen (filename);
1070 if ( (cmdlen < 5) || (0 != strcmp (&filename[cmdlen - 4], ".exe")) )
1071 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1073 GNUNET_asprintf (&non_const_filename, "%s", filename);
1075 /* It could be in POSIX form, convert it to a DOS path early on */
1076 if (ERROR_SUCCESS != (lRet = plibc_conv_to_win_path (non_const_filename, win_path)))
1078 SetErrnoFromWinError (lRet);
1079 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "plibc_conv_to_win_path",
1080 non_const_filename);
1081 GNUNET_free (non_const_filename);
1082 GNUNET_free (pathbuf);
1085 GNUNET_free (non_const_filename);
1086 non_const_filename = GNUNET_strdup (win_path);
1087 /* Check that this is the full path. If it isn't, search. */
1088 /* FIXME: convert it to wchar_t and use SearchPathW?
1089 * Remember: arguments to _start_process() are technically in UTF-8...
1091 if (non_const_filename[1] == ':')
1092 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1093 else if (!SearchPathA
1094 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1097 SetErrnoFromWinError (GetLastError ());
1098 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1099 non_const_filename);
1100 GNUNET_free (non_const_filename);
1101 GNUNET_free (pathbuf);
1104 GNUNET_free (pathbuf);
1105 GNUNET_free (non_const_filename);
1107 /* Count the number of arguments */
1108 arg = (char **) argv;
1115 /* Allocate a copy argv */
1116 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1118 /* Copy all argv strings */
1120 arg = (char **) argv;
1124 non_const_argv[argcount] = GNUNET_strdup (path);
1126 non_const_argv[argcount] = GNUNET_strdup (*arg);
1130 non_const_argv[argcount] = NULL;
1134 arg = non_const_argv;
1137 cmdlen = cmdlen + strlen (*arg) + 4;
1141 /* Allocate and create cmd */
1142 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1143 arg = non_const_argv;
1146 char arg_last_char = (*arg)[strlen (*arg) - 1];
1147 idx += sprintf (idx, "\"%s%s\"%s", *arg,
1148 arg_last_char == '\\' ? "\\" : "", *(arg + 1) ? " " : "");
1152 while (argcount > 0)
1153 GNUNET_free (non_const_argv[--argcount]);
1154 GNUNET_free (non_const_argv);
1156 memset (&start, 0, sizeof (start));
1157 start.cb = sizeof (start);
1158 if ((pipe_stdin != NULL) || (pipe_stdout != NULL) || (std_inheritance != 0))
1159 start.dwFlags |= STARTF_USESTDHANDLES;
1161 stdih = GetStdHandle (STD_INPUT_HANDLE);
1162 GetHandleInformation (stdih, &stdif);
1163 if (pipe_stdin != NULL)
1165 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1166 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
1167 &stdin_handle, sizeof (HANDLE));
1168 start.hStdInput = stdin_handle;
1172 if (std_inheritance & GNUNET_OS_INHERIT_STD_IN)
1174 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 1);
1175 if (pipe_stdin == NULL)
1176 start.hStdInput = stdih;
1179 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 0);
1183 stdoh = GetStdHandle (STD_OUTPUT_HANDLE);
1184 GetHandleInformation (stdoh, &stdof);
1185 if (NULL != pipe_stdout)
1187 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1189 GNUNET_DISK_PIPE_END_WRITE),
1190 &stdout_handle, sizeof (HANDLE));
1191 start.hStdOutput = stdout_handle;
1195 if (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)
1197 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 1);
1198 if (pipe_stdout == NULL)
1199 start.hStdOutput = stdoh;
1202 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 0);
1205 stdeh = GetStdHandle (STD_ERROR_HANDLE);
1206 GetHandleInformation (stdeh, &stdef);
1209 if (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)
1211 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 1);
1212 start.hStdError = stdeh;
1215 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 0);
1218 if (GNUNET_YES == pipe_control)
1221 npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1222 GNUNET_DISK_PERM_USER_READ |
1223 GNUNET_DISK_PERM_USER_WRITE);
1224 if (control_pipe == NULL)
1232 control_pipe = NULL;
1233 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1235 lsocks_pipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
1237 if (lsocks_pipe == NULL)
1241 GNUNET_DISK_pipe_close (lsocks_pipe);
1244 lsocks_write_fd = GNUNET_DISK_pipe_handle (lsocks_pipe,
1245 GNUNET_DISK_PIPE_END_WRITE);
1246 GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1247 &lsocks_write, sizeof (HANDLE));
1248 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
1249 (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1250 &lsocks_read, sizeof (HANDLE));
1254 if (NULL != childpipename)
1256 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1258 GNUNET_asprintf (&our_env[env_off++], "%s=", GNUNET_OS_CONTROL_PIPE);
1259 GNUNET_asprintf (&our_env[env_off++], "%s", childpipename);
1260 GNUNET_free (childpipename);
1262 if ( (lsocks != NULL) && (lsocks[0] != INVALID_SOCKET))
1264 /*This will tell the child that we're going to send lsocks over the pipe*/
1265 GNUNET_asprintf (&our_env[env_off++], "%s=", "GNUNET_OS_READ_LSOCKS");
1266 GNUNET_asprintf (&our_env[env_off++], "%lu", lsocks_read);
1268 our_env[env_off++] = NULL;
1269 env_block = CreateCustomEnvTable (our_env);
1271 GNUNET_free_non_null (our_env[--env_off]);
1274 if (NULL == (wpath = u8_to_u16 ((uint8_t *) path, 1 + strlen (path), NULL, &wpath_len)))
1276 LOG (GNUNET_ERROR_TYPE_DEBUG,
1277 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", path, errno);
1278 GNUNET_free (env_block);
1284 if (NULL == (wcmd = u8_to_u16 ((uint8_t *) cmd, 1 + strlen (cmd), NULL, &wcmd_len)))
1286 LOG (GNUNET_ERROR_TYPE_DEBUG,
1287 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", cmd, errno);
1288 GNUNET_free (env_block);
1294 bresult = CreateProcessW (wpath, wcmd, NULL, NULL, TRUE,
1295 DETACHED_PROCESS | CREATE_SUSPENDED, env_block, NULL, &start, &proc);
1296 error_code = GetLastError ();
1298 if ((NULL == pipe_stdin) && (stdih))
1299 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, stdif);
1302 if ((NULL == pipe_stdout) && (stdoh))
1303 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, stdof);
1306 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, stdef);
1308 GNUNET_free (env_block);
1315 SetErrnoFromWinError (error_code);
1316 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1317 if (NULL != control_pipe)
1318 GNUNET_DISK_file_close (control_pipe);
1320 GNUNET_DISK_pipe_close (lsocks_pipe);
1324 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1325 gnunet_proc->pid = proc.dwProcessId;
1326 gnunet_proc->handle = proc.hProcess;
1327 gnunet_proc->control_pipe = control_pipe;
1329 CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL);
1331 ResumeThread (proc.hThread);
1332 CloseHandle (proc.hThread);
1334 if ( (NULL == lsocks) || (INVALID_SOCKET == lsocks[0]) )
1337 GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1339 /* This is a replacement for "goto error" that doesn't use goto */
1348 /* Tell the number of sockets */
1349 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++);
1351 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1352 if (sizeof (count) != wrote)
1354 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1355 "Failed to write %u count bytes to the child: %u\n",
1356 sizeof (count), GetLastError ());
1359 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1361 WSAPROTOCOL_INFOA pi;
1362 /* Get a socket duplication info */
1363 if (SOCKET_ERROR == WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi))
1365 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1366 "Failed to duplicate an socket[%llu]: %u\n", i,
1370 /* Synchronous I/O is not nice, but we can't schedule this:
1371 * lsocks will be closed/freed by the caller soon, and until
1372 * the child creates a duplicate, closing a socket here will
1373 * close it for good.
1375 /* Send the size of the structure
1376 * (the child might be built with different headers...)
1379 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size));
1380 if (sizeof (size) != wrote)
1382 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1383 "Failed to write %u size[%llu] bytes to the child: %u\n",
1384 sizeof (size), i, GetLastError ());
1387 /* Finally! Send the data */
1388 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1389 if (sizeof (pi) != wrote)
1391 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1392 "Failed to write %u socket[%llu] bytes to the child: %u\n",
1393 sizeof (pi), i, GetLastError ());
1397 /* This will block us until the child makes a final read or closes
1398 * the pipe (hence no 'wrote' check), since we have to wait for it
1399 * to duplicate the last socket, before we return and start closing
1402 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1407 GNUNET_DISK_file_sync (lsocks_write_fd);
1408 GNUNET_DISK_pipe_close (lsocks_pipe);
1412 /* If we can't pass on the socket(s), the child will block forever,
1413 * better put it out of its misery.
1415 SafeTerminateProcess (gnunet_proc->handle, 0, 0);
1416 CloseHandle (gnunet_proc->handle);
1417 if (NULL != gnunet_proc->control_pipe)
1418 GNUNET_DISK_file_close (gnunet_proc->control_pipe);
1419 GNUNET_free (gnunet_proc);
1432 * @param pipe_control should a pipe be used to send signals to the child?
1433 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1434 * @param pipe_stdin pipe to use to send input to child process (or NULL)
1435 * @param pipe_stdout pipe to use to get output from child process (or NULL)
1436 * @param filename name of the binary
1437 * @param argv NULL-terminated array of arguments to the process
1438 * @return pointer to process structure of the new process, NULL on error
1440 struct GNUNET_OS_Process *
1441 GNUNET_OS_start_process_vap (int pipe_control,
1442 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1443 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1444 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1445 const char *filename,
1448 return start_process (pipe_control,
1461 * @param pipe_control should a pipe be used to send signals to the child?
1462 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1463 * @param pipe_stdin pipe to use to send input to child process (or NULL)
1464 * @param pipe_stdout pipe to use to get output from child process (or NULL)
1465 * @param filename name of the binary
1466 * @param va NULL-terminated list of arguments to the process
1467 * @return pointer to process structure of the new process, NULL on error
1469 struct GNUNET_OS_Process *
1470 GNUNET_OS_start_process_va (int pipe_control,
1471 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1472 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1473 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1474 const char *filename, va_list va)
1476 struct GNUNET_OS_Process *ret;
1483 while (NULL != va_arg (ap, char *))
1486 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
1489 while (NULL != (argv[argc] = va_arg (ap, char *)))
1492 ret = GNUNET_OS_start_process_vap (pipe_control,
1506 * @param pipe_control should a pipe be used to send signals to the child?
1507 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags
1508 * @param pipe_stdin pipe to use to send input to child process (or NULL)
1509 * @param pipe_stdout pipe to use to get output from child process (or NULL)
1510 * @param filename name of the binary
1511 * @param ... NULL-terminated list of arguments to the process
1512 * @return pointer to process structure of the new process, NULL on error
1514 struct GNUNET_OS_Process *
1515 GNUNET_OS_start_process (int pipe_control,
1516 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1517 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1518 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1519 const char *filename, ...)
1521 struct GNUNET_OS_Process *ret;
1524 va_start (ap, filename);
1525 ret = GNUNET_OS_start_process_va (pipe_control, std_inheritance, pipe_stdin,
1526 pipe_stdout, filename, ap);
1535 * @param pipe_control should a pipe be used to send signals to the child?
1536 * @param std_inheritance a set of GNUNET_OS_INHERIT_STD_* flags controlling which
1537 * std handles of the parent are inherited by the child.
1538 * pipe_stdin and pipe_stdout take priority over std_inheritance
1539 * (when they are non-NULL).
1540 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
1541 * must be NULL on platforms where dup is not supported
1542 * @param filename name of the binary
1543 * @param argv NULL-terminated list of arguments to the process
1544 * @return process ID of the new process, -1 on error
1546 struct GNUNET_OS_Process *
1547 GNUNET_OS_start_process_v (int pipe_control,
1548 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1549 const SOCKTYPE *lsocks,
1550 const char *filename,
1553 return start_process (pipe_control,
1564 * Retrieve the status of a process, waiting on him if dead.
1565 * Nonblocking version.
1567 * @param proc process ID
1568 * @param type status type
1569 * @param code return code/signal number
1570 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1573 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1574 enum GNUNET_OS_ProcessStatusType *type,
1575 unsigned long *code)
1581 GNUNET_assert (0 != proc);
1582 ret = waitpid (proc->pid, &status, WNOHANG);
1585 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1586 return GNUNET_SYSERR;
1590 *type = GNUNET_OS_PROCESS_RUNNING;
1594 if (proc->pid != ret)
1596 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1597 return GNUNET_SYSERR;
1599 if (WIFEXITED (status))
1601 *type = GNUNET_OS_PROCESS_EXITED;
1602 *code = WEXITSTATUS (status);
1604 else if (WIFSIGNALED (status))
1606 *type = GNUNET_OS_PROCESS_SIGNALED;
1607 *code = WTERMSIG (status);
1609 else if (WIFSTOPPED (status))
1611 *type = GNUNET_OS_PROCESS_SIGNALED;
1612 *code = WSTOPSIG (status);
1615 else if (WIFCONTINUED (status))
1617 *type = GNUNET_OS_PROCESS_RUNNING;
1623 *type = GNUNET_OS_PROCESS_UNKNOWN;
1628 DWORD c, error_code, ret;
1632 if (h == NULL || ret == 0)
1634 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1636 return GNUNET_SYSERR;
1639 h = GetCurrentProcess ();
1642 ret = GetExitCodeProcess (h, &c);
1643 error_code = GetLastError ();
1644 if (ret == 0 || error_code != NO_ERROR)
1646 SetErrnoFromWinError (error_code);
1647 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1648 return GNUNET_SYSERR;
1650 if (STILL_ACTIVE == c)
1652 *type = GNUNET_OS_PROCESS_RUNNING;
1656 *type = GNUNET_OS_PROCESS_EXITED;
1665 * Wait for a process
1667 * @param proc pointer to process structure
1668 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1671 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1674 pid_t pid = proc->pid;
1677 while ( (pid != (ret = waitpid (pid, NULL, 0))) &&
1678 (EINTR == errno) ) ;
1681 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1682 return GNUNET_SYSERR;
1691 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1693 return GNUNET_SYSERR;
1696 h = GetCurrentProcess ();
1698 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1700 SetErrnoFromWinError (GetLastError ());
1701 return GNUNET_SYSERR;
1709 * Handle to a command.
1711 struct GNUNET_OS_CommandHandle
1717 struct GNUNET_OS_Process *eip;
1720 * Handle to the output pipe.
1722 struct GNUNET_DISK_PipeHandle *opipe;
1725 * Read-end of output pipe.
1727 const struct GNUNET_DISK_FileHandle *r;
1730 * Function to call on each line of output.
1732 GNUNET_OS_LineProcessor proc;
1735 * Closure for 'proc'.
1740 * Buffer for the output.
1745 * Task reading from pipe.
1747 GNUNET_SCHEDULER_TaskIdentifier rtask;
1752 struct GNUNET_TIME_Absolute timeout;
1755 * Current read offset in buf.
1762 * Stop/kill a command. Must ONLY be called either from
1763 * the callback after 'NULL' was passed for 'line' *OR*
1764 * from an independent task (not within the line processor).
1766 * @param cmd handle to the process
1769 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1771 if (NULL != cmd->proc)
1773 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1774 GNUNET_SCHEDULER_cancel (cmd->rtask);
1776 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1777 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1778 GNUNET_OS_process_destroy (cmd->eip);
1779 GNUNET_DISK_pipe_close (cmd->opipe);
1785 * Read from the process and call the line processor.
1787 * @param cls the 'struct GNUNET_OS_CommandHandle'
1788 * @param tc scheduler context
1791 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1793 struct GNUNET_OS_CommandHandle *cmd = cls;
1794 GNUNET_OS_LineProcessor proc;
1798 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1799 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1801 /* timeout, shutdown, etc. */
1804 proc (cmd->proc_cls, NULL);
1808 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1809 sizeof (cmd->buf) - cmd->off);
1812 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1814 cmd->buf[cmd->off] = '\0';
1815 cmd->proc (cmd->proc_cls, cmd->buf);
1819 proc (cmd->proc_cls, NULL);
1822 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1827 cmd->proc (cmd->proc_cls, cmd->buf);
1828 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1829 cmd->off -= (end + 1 - cmd->buf);
1830 end = memchr (cmd->buf, '\n', cmd->off);
1833 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1834 (cmd->timeout), cmd->r, &cmd_read, cmd);
1839 * Run the given command line and call the given function
1840 * for each line of the output.
1842 * @param proc function to call for each line of the output
1843 * @param proc_cls closure for proc
1844 * @param timeout when to time out
1845 * @param binary command to run
1846 * @param ... arguments to command
1847 * @return NULL on error
1849 struct GNUNET_OS_CommandHandle *
1850 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1851 struct GNUNET_TIME_Relative timeout, const char *binary,
1854 struct GNUNET_OS_CommandHandle *cmd;
1855 struct GNUNET_OS_Process *eip;
1856 struct GNUNET_DISK_PipeHandle *opipe;
1859 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1862 va_start (ap, binary);
1863 /* redirect stdout, don't inherit stderr/stdin */
1864 eip = GNUNET_OS_start_process_va (GNUNET_NO, 0, NULL, opipe, binary, ap);
1868 GNUNET_DISK_pipe_close (opipe);
1871 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1872 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1873 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1877 cmd->proc_cls = proc_cls;
1878 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1879 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1884 /* end of os_priority.c */