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"
33 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
35 struct GNUNET_OS_Process
42 struct GNUNET_DISK_FileHandle *control_pipe;
45 static struct GNUNET_OS_Process current_process;
49 * This handler is called when there are control data to be read on the pipe
51 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
52 * @param tc scheduler context
55 parent_control_handler (void *cls,
56 const struct GNUNET_SCHEDULER_TaskContext *tc)
58 struct GNUNET_DISK_FileHandle *control_pipe =
59 (struct GNUNET_DISK_FileHandle *) cls;
63 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n",
64 __FUNCTION__, tc->reason);
67 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT |
68 GNUNET_SCHEDULER_REASON_PREREQ_DONE))
70 GNUNET_DISK_npipe_close (control_pipe);
74 if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) !=
77 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
78 GNUNET_DISK_npipe_close (control_pipe);
83 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n",
86 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
87 control_pipe, &parent_control_handler,
96 * Task that connects this process to its parent via pipe
99 GNUNET_OS_install_parent_control_handler (void *cls,
101 GNUNET_SCHEDULER_TaskContext *tc)
104 struct GNUNET_DISK_FileHandle *control_pipe;
106 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
107 if ((env_buf == NULL) || (strlen (env_buf) <= 0))
109 GNUNET_log (GNUNET_ERROR_TYPE_INFO,
110 _("Not installing a handler because $%s=%s\n"),
111 GNUNET_OS_CONTROL_PIPE, env_buf);
115 GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
116 GNUNET_DISK_PERM_USER_READ |
117 GNUNET_DISK_PERM_USER_WRITE);
118 if (control_pipe == NULL)
120 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
124 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
125 "Adding parent control handler pipe `%s' to the scheduler\n",
128 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
129 &parent_control_handler, control_pipe);
134 * Get process structure for current process
136 * The pointer it returns points to static memory location and must not be
139 * @return pointer to the process sturcutre for this process
141 struct GNUNET_OS_Process *
142 GNUNET_OS_process_current ()
145 current_process.pid = GetCurrentProcessId ();
146 current_process.handle = GetCurrentProcess ();
148 current_process.pid = 0;
150 return ¤t_process;
155 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
157 #if ENABLE_WINDOWS_WORKAROUNDS
161 ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
162 if (ret != sizeof (sig))
166 /* Child process is not controllable via pipe */
168 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
169 "Child process is not controllable, will kill it directly\n");
172 else if (errno == EPIPE)
175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
176 "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
180 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
181 "Failed to write into control pipe , errno is %d\n", errno);
182 #if WINDOWS && !defined(__CYGWIN__)
183 TerminateProcess (proc->handle, 0);
185 PLIBC_KILL (proc->pid, sig);
191 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
192 "Wrote control code into control pipe, now waiting\n");
196 /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
197 if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
198 TerminateProcess (proc->handle, 0);
201 struct GNUNET_NETWORK_FDSet *rfds;
202 struct GNUNET_NETWORK_FDSet *efds;
204 rfds = GNUNET_NETWORK_fdset_create ();
205 efds = GNUNET_NETWORK_fdset_create ();
207 GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
208 GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
210 /* Ndurner thought this up, and i have no idea what it does.
211 * There's have never been any code to answer the shutdown call
212 * (write a single int into the pipe, so that this function can read it).
213 * On *nix select() will probably tell that pipe is ready
214 * for reading, once the other process shuts down,
215 * but the read () call will fail, triggering a kill ()
216 * on the pid that is already dead. This will probably result in non-0
217 * return from kill(), and therefore from this function.
222 GNUNET_NETWORK_socket_select (rfds, NULL, efds,
223 GNUNET_TIME_relative_multiply
224 (GNUNET_TIME_relative_get_unit (),
228 GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
230 /* Just to be sure */
231 PLIBC_KILL (proc->pid, sig);
237 if (GNUNET_DISK_file_read (proc->control_pipe, &ret, sizeof (ret)) !=
239 res = PLIBC_KILL (proc->pid, sig);
241 /* Child signaled shutdown is in progress */
250 return kill (proc->pid, sig);
255 * Get the pid of the process in question
257 * @param proc the process to get the pid of
259 * @return the current process id
262 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
269 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
271 #if ENABLE_WINDOWS_WORKAROUNDS
272 if (proc->control_pipe)
273 GNUNET_DISK_npipe_close (proc->control_pipe);
277 if (proc->handle != NULL)
278 CloseHandle (proc->handle);
285 #include "gnunet_signal_lib.h"
287 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
290 * Make seaspider happy.
292 #define DWORD_WINAPI DWORD WINAPI
295 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
296 * @param proc pointer to process structure
299 ChildWaitThread (void *arg)
301 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
303 WaitForSingleObject (proc->handle, INFINITE);
305 if (w32_sigchld_handler)
306 w32_sigchld_handler ();
313 * Set process priority
315 * @param proc pointer to process structure
316 * @param prio priority value
317 * @return GNUNET_OK on success, GNUNET_SYSERR on error
320 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
321 enum GNUNET_SCHEDULER_Priority prio)
325 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
326 if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
329 /* convert to MINGW/Unix values */
332 case GNUNET_SCHEDULER_PRIORITY_UI:
333 case GNUNET_SCHEDULER_PRIORITY_URGENT:
335 rprio = HIGH_PRIORITY_CLASS;
341 case GNUNET_SCHEDULER_PRIORITY_HIGH:
343 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
349 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
351 rprio = NORMAL_PRIORITY_CLASS;
357 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
359 rprio = BELOW_NORMAL_PRIORITY_CLASS;
365 case GNUNET_SCHEDULER_PRIORITY_IDLE:
367 rprio = IDLE_PRIORITY_CLASS;
374 return GNUNET_SYSERR;
377 /* Set process priority */
380 HANDLE h = proc->handle;
382 GNUNET_assert (h != NULL);
383 SetPriorityClass (h, rprio);
389 if ((0 == pid) || (pid == getpid ()))
392 int delta = rprio - have;
395 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
397 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
399 return GNUNET_SYSERR;
404 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
406 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
408 return GNUNET_SYSERR;
413 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
414 "Priority management not availabe for this platform\n");
422 CreateCustomEnvTable (char **vars)
424 char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
425 size_t tablesize = 0;
426 size_t items_count = 0;
427 size_t n_found = 0, n_var;
434 win32_env_table = GetEnvironmentStringsA ();
435 if (win32_env_table == NULL)
437 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
439 index = GNUNET_malloc (sizeof (char *) * n_var);
440 for (c = 0; c < n_var; c++)
442 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
444 size_t len = strlen (ptr);
447 for (var_ptr = vars; *var_ptr; var_ptr++)
451 var_len = strlen (var);
452 if (strncmp (var, ptr, var_len) == 0)
456 tablesize += var_len + strlen (val) + 1;
461 tablesize += len + 1;
464 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
469 n_found += strlen (var) + strlen (val) + 1;
471 result = GNUNET_malloc (tablesize + n_found + 1);
472 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
474 size_t len = strlen (ptr);
477 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
481 var_len = strlen (var);
482 if (strncmp (var, ptr, var_len) == 0)
490 strcpy (result_ptr, ptr);
491 result_ptr += len + 1;
495 strcpy (result_ptr, var);
496 result_ptr += var_len;
497 strcpy (result_ptr, val);
498 result_ptr += strlen (val) + 1;
502 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
506 var_len = strlen (var);
509 strcpy (result_ptr, var);
510 result_ptr += var_len;
511 strcpy (result_ptr, val);
512 result_ptr += strlen (val) + 1;
515 FreeEnvironmentStrings (win32_env_table);
526 * @param pipe_stdin pipe to use to send input to child process (or NULL)
527 * @param pipe_stdout pipe to use to get output from child process (or NULL)
528 * @param filename name of the binary
529 * @param va NULL-terminated list of arguments to the process
530 * @return pointer to process structure of the new process, NULL on error
532 struct GNUNET_OS_Process *
533 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
534 struct GNUNET_DISK_PipeHandle *pipe_stdout,
535 const char *filename, va_list va)
539 #if ENABLE_WINDOWS_WORKAROUNDS
540 char *childpipename = NULL;
541 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
543 struct GNUNET_OS_Process *gnunet_proc = NULL;
554 #if ENABLE_WINDOWS_WORKAROUNDS
556 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
557 GNUNET_DISK_PERM_USER_READ |
558 GNUNET_DISK_PERM_USER_WRITE);
559 if (control_pipe == NULL)
565 while (NULL != va_arg (ap, char *))
569 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
572 while (NULL != (argv[argc] = va_arg (ap, char *)))
576 if (pipe_stdout != NULL)
578 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
580 GNUNET_DISK_PIPE_END_WRITE),
581 &fd_stdout_write, sizeof (int));
582 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
583 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
584 &fd_stdout_read, sizeof (int));
586 if (pipe_stdin != NULL)
588 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
589 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
590 &fd_stdin_read, sizeof (int));
591 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
592 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
593 &fd_stdin_write, sizeof (int));
596 #if HAVE_WORKING_VFORK
605 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
606 #if ENABLE_WINDOWS_WORKAROUNDS
607 GNUNET_DISK_npipe_close (control_pipe);
613 #if HAVE_WORKING_VFORK
614 /* let's hope vfork actually works; for some extreme cases (including
615 * a testcase) we need 'execvp' to have run before we return, since
616 * we may send a signal to the process next and we don't want it
617 * to be caught by OUR signal handler (but either by the default
618 * handler or the actual handler as installed by the process itself). */
620 /* let's give the child process a chance to run execvp, 1s should
621 * be plenty in practice */
622 if (pipe_stdout != NULL)
623 GNUNET_DISK_pipe_close_end (pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
624 if (pipe_stdin != NULL)
625 GNUNET_DISK_pipe_close_end (pipe_stdin, GNUNET_DISK_PIPE_END_READ);
628 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
629 gnunet_proc->pid = ret;
630 #if ENABLE_WINDOWS_WORKAROUNDS
631 gnunet_proc->control_pipe = control_pipe;
635 #if ENABLE_WINDOWS_WORKAROUNDS
636 GNUNET_free (childpipename);
641 #if ENABLE_WINDOWS_WORKAROUNDS
642 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
643 GNUNET_free (childpipename);
646 if (pipe_stdout != NULL)
648 GNUNET_break (0 == close (fd_stdout_read));
649 if (-1 == dup2 (fd_stdout_write, 1))
650 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
651 GNUNET_break (0 == close (fd_stdout_write));
654 if (pipe_stdin != NULL)
657 GNUNET_break (0 == close (fd_stdin_write));
658 if (-1 == dup2 (fd_stdin_read, 0))
659 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2");
660 GNUNET_break (0 == close (fd_stdin_read));
662 execvp (filename, argv);
663 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
670 PROCESS_INFORMATION proc;
673 HANDLE stdout_handle;
675 char path[MAX_PATH + 1];
677 char *our_env[3] = { NULL, NULL, NULL };
678 char *env_block = NULL;
680 DWORD pathbuf_len, alloc_len;
685 char *non_const_filename;
687 /* Search in prefix dir (hopefully - the directory from which
688 * the current module was loaded), bindir and libdir, then in PATH
690 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
691 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
692 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
694 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
697 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
700 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
703 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
704 GNUNET_free (self_prefix);
705 GNUNET_free (bindir);
706 GNUNET_free (libdir);
708 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
709 GNUNET_assert (alloc_len == (pathbuf_len - 1));
711 cmdlen = strlen (filename);
712 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
713 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
715 GNUNET_asprintf (&non_const_filename, "%s", filename);
717 /* Check that this is the full path. If it isn't, search. */
718 if (non_const_filename[1] == ':')
719 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
720 else if (!SearchPathA
721 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
724 SetErrnoFromWinError (GetLastError ());
725 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
727 GNUNET_free (non_const_filename);
728 GNUNET_free (pathbuf);
731 GNUNET_free (pathbuf);
732 GNUNET_free (non_const_filename);
736 while (NULL != (arg = va_arg (ap, char *)))
739 cmdlen = cmdlen + strlen (path) + 3;
741 cmdlen = cmdlen + strlen (arg) + 3;
745 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
747 while (NULL != (arg = va_arg (ap, char *)))
750 idx += sprintf (idx, "\"%s\" ", path);
752 idx += sprintf (idx, "\"%s\" ", arg);
756 memset (&start, 0, sizeof (start));
757 start.cb = sizeof (start);
759 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
760 start.dwFlags |= STARTF_USESTDHANDLES;
762 if (pipe_stdin != NULL)
764 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
765 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
766 &stdin_handle, sizeof (HANDLE));
767 start.hStdInput = stdin_handle;
770 if (pipe_stdout != NULL)
772 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
774 GNUNET_DISK_PIPE_END_WRITE),
775 &stdout_handle, sizeof (HANDLE));
776 start.hStdOutput = stdout_handle;
780 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
781 GNUNET_DISK_PERM_USER_READ |
782 GNUNET_DISK_PERM_USER_WRITE);
783 if (control_pipe == NULL)
791 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
792 "Opened the parent end of the pipe `%s'\n", childpipename);
795 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
796 GNUNET_asprintf (&our_env[1], "%s", childpipename);
798 env_block = CreateCustomEnvTable (our_env);
799 GNUNET_free (our_env[0]);
800 GNUNET_free (our_env[1]);
803 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
804 env_block, NULL, &start, &proc))
806 SetErrnoFromWinError (GetLastError ());
807 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
808 GNUNET_free (env_block);
813 GNUNET_free (env_block);
815 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
816 gnunet_proc->pid = proc.dwProcessId;
817 gnunet_proc->handle = proc.hProcess;
818 gnunet_proc->control_pipe = control_pipe;
820 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
822 ResumeThread (proc.hThread);
823 CloseHandle (proc.hThread);
835 * @param pipe_stdin pipe to use to send input to child process (or NULL)
836 * @param pipe_stdout pipe to use to get output from child process (or NULL)
837 * @param filename name of the binary
838 * @param ... NULL-terminated list of arguments to the process
840 * @return pointer to process structure of the new process, NULL on error
843 struct GNUNET_OS_Process *
844 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
845 struct GNUNET_DISK_PipeHandle *pipe_stdout,
846 const char *filename, ...)
848 struct GNUNET_OS_Process *ret;
851 va_start (ap, filename);
852 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
861 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
862 * must be NULL on platforms where dup is not supported
863 * @param filename name of the binary
864 * @param argv NULL-terminated list of arguments to the process
865 * @return process ID of the new process, -1 on error
867 struct GNUNET_OS_Process *
868 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
871 #if ENABLE_WINDOWS_WORKAROUNDS
872 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
873 char *childpipename = NULL;
880 struct GNUNET_OS_Process *gnunet_proc = NULL;
889 #if ENABLE_WINDOWS_WORKAROUNDS
891 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
892 GNUNET_DISK_PERM_USER_READ |
893 GNUNET_DISK_PERM_USER_WRITE);
894 if (control_pipe == NULL)
903 while (-1 != (k = lsocks[i++]))
904 GNUNET_array_append (lscp, ls, k);
905 GNUNET_array_append (lscp, ls, -1);
907 #if HAVE_WORKING_VFORK
916 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "fork");
917 #if ENABLE_WINDOWS_WORKAROUNDS
918 GNUNET_DISK_npipe_close (control_pipe);
923 #if HAVE_WORKING_VFORK
924 /* let's hope vfork actually works; for some extreme cases (including
925 * a testcase) we need 'execvp' to have run before we return, since
926 * we may send a signal to the process next and we don't want it
927 * to be caught by OUR signal handler (but either by the default
928 * handler or the actual handler as installed by the process itself). */
930 /* let's give the child process a chance to run execvp, 1s should
931 * be plenty in practice */
934 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
935 gnunet_proc->pid = ret;
936 #if ENABLE_WINDOWS_WORKAROUNDS
937 gnunet_proc->control_pipe = control_pipe;
941 GNUNET_array_grow (lscp, ls, 0);
942 #if ENABLE_WINDOWS_WORKAROUNDS
943 GNUNET_free (childpipename);
948 #if ENABLE_WINDOWS_WORKAROUNDS
949 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
950 GNUNET_free (childpipename);
955 /* read systemd documentation... */
956 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
957 setenv ("LISTEN_PID", lpid, 1);
960 while (-1 != lscp[i])
963 while (-1 != lscp[j])
969 GNUNET_assert (-1 != k);
970 GNUNET_assert (0 == close (lscp[j]));
978 /* Bury any existing FD, no matter what; they should all be closed
979 * on exec anyway and the important onces have been dup'ed away */
981 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
983 /* unset close-on-exec flag */
984 flags = fcntl (tgt, F_GETFD);
985 GNUNET_assert (flags >= 0);
986 flags &= ~FD_CLOEXEC;
988 (void) fcntl (tgt, F_SETFD, flags);
992 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
993 setenv ("LISTEN_FDS", fds, 1);
995 GNUNET_array_grow (lscp, ls, 0);
996 execvp (filename, argv);
997 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
1000 char **arg, **non_const_argv;
1001 unsigned int cmdlen;
1004 PROCESS_INFORMATION proc;
1006 struct GNUNET_OS_Process *gnunet_proc = NULL;
1008 char path[MAX_PATH + 1];
1010 char *our_env[3] = { NULL, NULL, NULL };
1011 char *env_block = NULL;
1013 DWORD pathbuf_len, alloc_len;
1018 char *non_const_filename;
1020 GNUNET_assert (lsocks == NULL);
1022 /* Search in prefix dir (hopefully - the directory from which
1023 * the current module was loaded), bindir and libdir, then in PATH
1025 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1026 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1027 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1029 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1032 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1035 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1038 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1039 GNUNET_free (self_prefix);
1040 GNUNET_free (bindir);
1041 GNUNET_free (libdir);
1043 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1044 if (alloc_len != pathbuf_len - 1)
1046 GNUNET_free (pathbuf);
1047 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1051 cmdlen = strlen (filename);
1052 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1053 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1055 GNUNET_asprintf (&non_const_filename, "%s", filename);
1057 /* Check that this is the full path. If it isn't, search. */
1058 if (non_const_filename[1] == ':')
1059 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1060 else if (!SearchPathA
1061 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1064 SetErrnoFromWinError (GetLastError ());
1065 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1066 non_const_filename);
1067 GNUNET_free (non_const_filename);
1068 GNUNET_free (pathbuf);
1071 GNUNET_free (pathbuf);
1072 GNUNET_free (non_const_filename);
1074 /* Count the number of arguments */
1075 arg = (char **) argv;
1082 /* Allocate a copy argv */
1083 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1085 /* Copy all argv strings */
1087 arg = (char **) argv;
1091 non_const_argv[argcount] = GNUNET_strdup (path);
1093 non_const_argv[argcount] = GNUNET_strdup (*arg);
1097 non_const_argv[argcount] = NULL;
1101 arg = non_const_argv;
1104 cmdlen = cmdlen + strlen (*arg) + 3;
1108 /* Allocate and create cmd */
1109 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1110 arg = non_const_argv;
1113 idx += sprintf (idx, "\"%s\" ", *arg);
1117 while (argcount > 0)
1118 GNUNET_free (non_const_argv[--argcount]);
1119 GNUNET_free (non_const_argv);
1121 memset (&start, 0, sizeof (start));
1122 start.cb = sizeof (start);
1125 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1126 GNUNET_DISK_PERM_USER_READ |
1127 GNUNET_DISK_PERM_USER_WRITE);
1128 if (control_pipe == NULL)
1136 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1137 "Opened the parent end of the pipe `%s'\n", childpipename);
1140 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1141 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1143 env_block = CreateCustomEnvTable (our_env);
1144 GNUNET_free (our_env[0]);
1145 GNUNET_free (our_env[1]);
1148 (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1149 env_block, NULL, &start, &proc))
1151 SetErrnoFromWinError (GetLastError ());
1152 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1153 GNUNET_free (env_block);
1158 GNUNET_free (env_block);
1160 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1161 gnunet_proc->pid = proc.dwProcessId;
1162 gnunet_proc->handle = proc.hProcess;
1163 gnunet_proc->control_pipe = control_pipe;
1165 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1167 ResumeThread (proc.hThread);
1168 CloseHandle (proc.hThread);
1177 * Retrieve the status of a process
1178 * @param proc process ID
1179 * @param type status type
1180 * @param code return code/signal number
1181 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1184 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1185 enum GNUNET_OS_ProcessStatusType *type,
1186 unsigned long *code)
1192 GNUNET_assert (0 != proc);
1193 ret = waitpid (proc->pid, &status, WNOHANG);
1196 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1197 return GNUNET_SYSERR;
1201 *type = GNUNET_OS_PROCESS_RUNNING;
1205 if (proc->pid != ret)
1207 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1208 return GNUNET_SYSERR;
1210 if (WIFEXITED (status))
1212 *type = GNUNET_OS_PROCESS_EXITED;
1213 *code = WEXITSTATUS (status);
1215 else if (WIFSIGNALED (status))
1217 *type = GNUNET_OS_PROCESS_SIGNALED;
1218 *code = WTERMSIG (status);
1220 else if (WIFSTOPPED (status))
1222 *type = GNUNET_OS_PROCESS_SIGNALED;
1223 *code = WSTOPSIG (status);
1226 else if (WIFCONTINUED (status))
1228 *type = GNUNET_OS_PROCESS_RUNNING;
1234 *type = GNUNET_OS_PROCESS_UNKNOWN;
1239 DWORD c, error_code, ret;
1243 if (h == NULL || ret == 0)
1245 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1246 "Invalid process information {%d, %08X}\n", ret, h);
1247 return GNUNET_SYSERR;
1250 h = GetCurrentProcess ();
1253 ret = GetExitCodeProcess (h, &c);
1254 error_code = GetLastError ();
1255 if (ret == 0 || error_code != NO_ERROR)
1257 SetErrnoFromWinError (error_code);
1258 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1259 return GNUNET_SYSERR;
1261 if (STILL_ACTIVE == c)
1263 *type = GNUNET_OS_PROCESS_RUNNING;
1267 *type = GNUNET_OS_PROCESS_EXITED;
1276 * Wait for a process
1277 * @param proc pointer to process structure
1278 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1281 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1285 pid_t pid = proc->pid;
1287 if (pid != waitpid (pid, NULL, 0))
1288 return GNUNET_SYSERR;
1297 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
1298 "Invalid process information {%d, %08X}\n", proc->pid, h);
1299 return GNUNET_SYSERR;
1302 h = GetCurrentProcess ();
1304 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1306 SetErrnoFromWinError (GetLastError ());
1307 ret = GNUNET_SYSERR;
1318 * Handle to a command.
1320 struct GNUNET_OS_CommandHandle
1326 struct GNUNET_OS_Process *eip;
1329 * Handle to the output pipe.
1331 struct GNUNET_DISK_PipeHandle *opipe;
1334 * Read-end of output pipe.
1336 const struct GNUNET_DISK_FileHandle *r;
1339 * Function to call on each line of output.
1341 GNUNET_OS_LineProcessor proc;
1344 * Closure for 'proc'.
1349 * Buffer for the output.
1354 * Task reading from pipe.
1356 GNUNET_SCHEDULER_TaskIdentifier rtask;
1361 struct GNUNET_TIME_Absolute timeout;
1364 * Current read offset in buf.
1371 * Stop/kill a command. Must ONLY be called either from
1372 * the callback after 'NULL' was passed for 'line' *OR*
1373 * from an independent task (not within the line processor).
1375 * @param cmd handle to the process
1378 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1381 if (cmd->proc != NULL)
1383 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1384 GNUNET_SCHEDULER_cancel (cmd->rtask);
1386 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1387 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1388 GNUNET_OS_process_close (cmd->eip);
1389 GNUNET_DISK_pipe_close (cmd->opipe);
1395 * Read from the process and call the line processor.
1397 * @param cls the 'struct GNUNET_OS_CommandHandle'
1398 * @param tc scheduler context
1401 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1403 struct GNUNET_OS_CommandHandle *cmd = cls;
1404 GNUNET_OS_LineProcessor proc;
1408 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1409 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1411 /* timeout, shutdown, etc. */
1414 proc (cmd->proc_cls, NULL);
1418 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1419 sizeof (cmd->buf) - cmd->off);
1422 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1424 cmd->buf[cmd->off] = '\0';
1425 cmd->proc (cmd->proc_cls, cmd->buf);
1429 proc (cmd->proc_cls, NULL);
1432 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1437 cmd->proc (cmd->proc_cls, cmd->buf);
1438 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1439 cmd->off -= (end + 1 - cmd->buf);
1440 end = memchr (cmd->buf, '\n', cmd->off);
1443 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1444 (cmd->timeout), cmd->r, &cmd_read, cmd);
1449 * Run the given command line and call the given function
1450 * for each line of the output.
1452 * @param proc function to call for each line of the output
1453 * @param proc_cls closure for proc
1454 * @param timeout when to time out
1455 * @param binary command to run
1456 * @param ... arguments to command
1457 * @return NULL on error
1459 struct GNUNET_OS_CommandHandle *
1460 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1461 struct GNUNET_TIME_Relative timeout, const char *binary,
1464 struct GNUNET_OS_CommandHandle *cmd;
1465 struct GNUNET_OS_Process *eip;
1466 struct GNUNET_DISK_PipeHandle *opipe;
1469 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1472 va_start (ap, binary);
1473 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1477 GNUNET_DISK_pipe_close (opipe);
1480 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1481 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1482 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1486 cmd->proc_cls = proc_cls;
1487 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1488 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1495 /* end of os_priority.c */