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 LOG(kind,...) GNUNET_log_from (kind, "util", __VA_ARGS__)
35 #define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util", syscall)
37 #define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util", syscall, filename)
39 #define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
41 struct GNUNET_OS_Process
48 struct GNUNET_DISK_FileHandle *control_pipe;
51 static struct GNUNET_OS_Process current_process;
55 * This handler is called when there are control data to be read on the pipe
57 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
58 * @param tc scheduler context
61 parent_control_handler (void *cls,
62 const struct GNUNET_SCHEDULER_TaskContext *tc)
64 struct GNUNET_DISK_FileHandle *control_pipe =
65 (struct GNUNET_DISK_FileHandle *) cls;
69 LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
73 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT |
74 GNUNET_SCHEDULER_REASON_PREREQ_DONE))
76 GNUNET_DISK_npipe_close (control_pipe);
80 if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) !=
83 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
84 GNUNET_DISK_npipe_close (control_pipe);
89 LOG (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
91 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
92 control_pipe, &parent_control_handler,
101 * Task that connects this process to its parent via pipe
104 GNUNET_OS_install_parent_control_handler (void *cls,
106 GNUNET_SCHEDULER_TaskContext *tc)
109 struct GNUNET_DISK_FileHandle *control_pipe;
111 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
112 if ((env_buf == NULL) || (strlen (env_buf) <= 0))
114 LOG (GNUNET_ERROR_TYPE_INFO, _("Not installing a handler because $%s=%s\n"),
115 GNUNET_OS_CONTROL_PIPE, env_buf);
119 GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
120 GNUNET_DISK_PERM_USER_READ |
121 GNUNET_DISK_PERM_USER_WRITE);
122 if (control_pipe == NULL)
124 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
128 LOG (GNUNET_ERROR_TYPE_DEBUG,
129 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
131 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
132 &parent_control_handler, control_pipe);
137 * Get process structure for current process
139 * The pointer it returns points to static memory location and must not be
142 * @return pointer to the process sturcutre for this process
144 struct GNUNET_OS_Process *
145 GNUNET_OS_process_current ()
148 current_process.pid = GetCurrentProcessId ();
149 current_process.handle = GetCurrentProcess ();
151 current_process.pid = 0;
153 return ¤t_process;
158 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
160 #if ENABLE_WINDOWS_WORKAROUNDS
164 ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
165 if (ret != sizeof (sig))
169 /* Child process is not controllable via pipe */
171 LOG (GNUNET_ERROR_TYPE_DEBUG,
172 "Child process is not controllable, will kill it directly\n");
175 else if (errno == EPIPE)
178 LOG (GNUNET_ERROR_TYPE_DEBUG,
179 "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
183 LOG (GNUNET_ERROR_TYPE_WARNING,
184 "Failed to write into control pipe , errno is %d\n", errno);
185 #if WINDOWS && !defined(__CYGWIN__)
186 TerminateProcess (proc->handle, 0);
188 PLIBC_KILL (proc->pid, sig);
194 LOG (GNUNET_ERROR_TYPE_DEBUG,
195 "Wrote control code into control pipe, now waiting\n");
199 /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
200 if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
201 TerminateProcess (proc->handle, 0);
204 struct GNUNET_NETWORK_FDSet *rfds;
205 struct GNUNET_NETWORK_FDSet *efds;
207 rfds = GNUNET_NETWORK_fdset_create ();
208 efds = GNUNET_NETWORK_fdset_create ();
210 GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
211 GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
213 /* Ndurner thought this up, and i have no idea what it does.
214 * There's have never been any code to answer the shutdown call
215 * (write a single int into the pipe, so that this function can read it).
216 * On *nix select() will probably tell that pipe is ready
217 * for reading, once the other process shuts down,
218 * but the read () call will fail, triggering a kill ()
219 * on the pid that is already dead. This will probably result in non-0
220 * return from kill(), and therefore from this function.
225 GNUNET_NETWORK_socket_select (rfds, NULL, efds,
226 GNUNET_TIME_relative_multiply
227 (GNUNET_TIME_relative_get_unit (),
231 GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
233 /* Just to be sure */
234 PLIBC_KILL (proc->pid, sig);
240 if (GNUNET_DISK_file_read (proc->control_pipe, &ret, sizeof (ret)) !=
242 res = PLIBC_KILL (proc->pid, sig);
244 /* Child signaled shutdown is in progress */
253 return kill (proc->pid, sig);
258 * Get the pid of the process in question
260 * @param proc the process to get the pid of
262 * @return the current process id
265 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
272 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
274 #if ENABLE_WINDOWS_WORKAROUNDS
275 if (proc->control_pipe)
276 GNUNET_DISK_npipe_close (proc->control_pipe);
280 if (proc->handle != NULL)
281 CloseHandle (proc->handle);
288 #include "gnunet_signal_lib.h"
290 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
293 * Make seaspider happy.
295 #define DWORD_WINAPI DWORD WINAPI
298 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
299 * @param proc pointer to process structure
302 ChildWaitThread (void *arg)
304 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
306 WaitForSingleObject (proc->handle, INFINITE);
308 if (w32_sigchld_handler)
309 w32_sigchld_handler ();
316 * Set process priority
318 * @param proc pointer to process structure
319 * @param prio priority value
320 * @return GNUNET_OK on success, GNUNET_SYSERR on error
323 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
324 enum GNUNET_SCHEDULER_Priority prio)
328 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
329 if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
332 /* convert to MINGW/Unix values */
335 case GNUNET_SCHEDULER_PRIORITY_UI:
336 case GNUNET_SCHEDULER_PRIORITY_URGENT:
338 rprio = HIGH_PRIORITY_CLASS;
344 case GNUNET_SCHEDULER_PRIORITY_HIGH:
346 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
352 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
354 rprio = NORMAL_PRIORITY_CLASS;
360 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
362 rprio = BELOW_NORMAL_PRIORITY_CLASS;
368 case GNUNET_SCHEDULER_PRIORITY_IDLE:
370 rprio = IDLE_PRIORITY_CLASS;
377 return GNUNET_SYSERR;
380 /* Set process priority */
383 HANDLE h = proc->handle;
385 GNUNET_assert (h != NULL);
386 SetPriorityClass (h, rprio);
392 if ((0 == pid) || (pid == getpid ()))
395 int delta = rprio - have;
398 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
400 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
401 return GNUNET_SYSERR;
406 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
408 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
410 return GNUNET_SYSERR;
415 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
416 "Priority management not availabe for this platform\n");
424 CreateCustomEnvTable (char **vars)
426 char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
427 size_t tablesize = 0;
428 size_t items_count = 0;
429 size_t n_found = 0, n_var;
436 win32_env_table = GetEnvironmentStringsA ();
437 if (win32_env_table == NULL)
439 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
441 index = GNUNET_malloc (sizeof (char *) * n_var);
442 for (c = 0; c < n_var; c++)
444 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
446 size_t len = strlen (ptr);
449 for (var_ptr = vars; *var_ptr; var_ptr++)
453 var_len = strlen (var);
454 if (strncmp (var, ptr, var_len) == 0)
458 tablesize += var_len + strlen (val) + 1;
463 tablesize += len + 1;
466 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
471 n_found += strlen (var) + strlen (val) + 1;
473 result = GNUNET_malloc (tablesize + n_found + 1);
474 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
476 size_t len = strlen (ptr);
479 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
483 var_len = strlen (var);
484 if (strncmp (var, ptr, var_len) == 0)
492 strcpy (result_ptr, ptr);
493 result_ptr += len + 1;
497 strcpy (result_ptr, var);
498 result_ptr += var_len;
499 strcpy (result_ptr, val);
500 result_ptr += strlen (val) + 1;
504 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
508 var_len = strlen (var);
511 strcpy (result_ptr, var);
512 result_ptr += var_len;
513 strcpy (result_ptr, val);
514 result_ptr += strlen (val) + 1;
517 FreeEnvironmentStrings (win32_env_table);
528 * @param pipe_stdin pipe to use to send input to child process (or NULL)
529 * @param pipe_stdout pipe to use to get output from child process (or NULL)
530 * @param filename name of the binary
531 * @param va NULL-terminated list of arguments to the process
532 * @return pointer to process structure of the new process, NULL on error
534 struct GNUNET_OS_Process *
535 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
536 struct GNUNET_DISK_PipeHandle *pipe_stdout,
537 const char *filename, va_list va)
541 #if ENABLE_WINDOWS_WORKAROUNDS
542 char *childpipename = NULL;
543 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
545 struct GNUNET_OS_Process *gnunet_proc = NULL;
556 #if ENABLE_WINDOWS_WORKAROUNDS
558 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
559 GNUNET_DISK_PERM_USER_READ |
560 GNUNET_DISK_PERM_USER_WRITE);
561 if (control_pipe == NULL)
567 while (NULL != va_arg (ap, char *))
571 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
574 while (NULL != (argv[argc] = va_arg (ap, char *)))
578 if (pipe_stdout != NULL)
580 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
582 GNUNET_DISK_PIPE_END_WRITE),
583 &fd_stdout_write, sizeof (int));
584 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
585 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
586 &fd_stdout_read, sizeof (int));
588 if (pipe_stdin != NULL)
590 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
591 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
592 &fd_stdin_read, sizeof (int));
593 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
594 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
595 &fd_stdin_write, sizeof (int));
603 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
604 #if ENABLE_WINDOWS_WORKAROUNDS
605 GNUNET_DISK_npipe_close (control_pipe);
610 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
611 gnunet_proc->pid = ret;
612 #if ENABLE_WINDOWS_WORKAROUNDS
613 gnunet_proc->control_pipe = control_pipe;
617 #if ENABLE_WINDOWS_WORKAROUNDS
618 GNUNET_free (childpipename);
623 #if ENABLE_WINDOWS_WORKAROUNDS
624 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
625 GNUNET_free (childpipename);
628 if (pipe_stdout != NULL)
630 GNUNET_break (0 == close (fd_stdout_read));
631 if (-1 == dup2 (fd_stdout_write, 1))
632 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
633 GNUNET_break (0 == close (fd_stdout_write));
636 if (pipe_stdin != NULL)
639 GNUNET_break (0 == close (fd_stdin_write));
640 if (-1 == dup2 (fd_stdin_read, 0))
641 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
642 GNUNET_break (0 == close (fd_stdin_read));
644 execvp (filename, argv);
645 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
652 PROCESS_INFORMATION proc;
655 HANDLE stdout_handle;
657 char path[MAX_PATH + 1];
659 char *our_env[3] = { NULL, NULL, NULL };
660 char *env_block = NULL;
662 DWORD pathbuf_len, alloc_len;
667 char *non_const_filename;
669 /* Search in prefix dir (hopefully - the directory from which
670 * the current module was loaded), bindir and libdir, then in PATH
672 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
673 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
674 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
676 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
679 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
682 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
685 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
686 GNUNET_free (self_prefix);
687 GNUNET_free (bindir);
688 GNUNET_free (libdir);
690 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
691 GNUNET_assert (alloc_len == (pathbuf_len - 1));
693 cmdlen = strlen (filename);
694 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
695 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
697 GNUNET_asprintf (&non_const_filename, "%s", filename);
699 /* Check that this is the full path. If it isn't, search. */
700 if (non_const_filename[1] == ':')
701 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
702 else if (!SearchPathA
703 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
706 SetErrnoFromWinError (GetLastError ());
707 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
709 GNUNET_free (non_const_filename);
710 GNUNET_free (pathbuf);
713 GNUNET_free (pathbuf);
714 GNUNET_free (non_const_filename);
718 while (NULL != (arg = va_arg (ap, char *)))
721 cmdlen = cmdlen + strlen (path) + 3;
723 cmdlen = cmdlen + strlen (arg) + 3;
727 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
729 while (NULL != (arg = va_arg (ap, char *)))
732 idx += sprintf (idx, "\"%s\" ", path);
734 idx += sprintf (idx, "\"%s\" ", arg);
738 memset (&start, 0, sizeof (start));
739 start.cb = sizeof (start);
741 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
742 start.dwFlags |= STARTF_USESTDHANDLES;
744 if (pipe_stdin != NULL)
746 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
747 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
748 &stdin_handle, sizeof (HANDLE));
749 start.hStdInput = stdin_handle;
752 if (pipe_stdout != NULL)
754 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
756 GNUNET_DISK_PIPE_END_WRITE),
757 &stdout_handle, sizeof (HANDLE));
758 start.hStdOutput = stdout_handle;
762 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
763 GNUNET_DISK_PERM_USER_READ |
764 GNUNET_DISK_PERM_USER_WRITE);
765 if (control_pipe == NULL)
773 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
777 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
778 GNUNET_asprintf (&our_env[1], "%s", childpipename);
780 env_block = CreateCustomEnvTable (our_env);
781 GNUNET_free (our_env[0]);
782 GNUNET_free (our_env[1]);
785 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
786 env_block, NULL, &start, &proc))
788 SetErrnoFromWinError (GetLastError ());
789 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
790 GNUNET_free (env_block);
795 GNUNET_free (env_block);
797 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
798 gnunet_proc->pid = proc.dwProcessId;
799 gnunet_proc->handle = proc.hProcess;
800 gnunet_proc->control_pipe = control_pipe;
802 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
804 ResumeThread (proc.hThread);
805 CloseHandle (proc.hThread);
817 * @param pipe_stdin pipe to use to send input to child process (or NULL)
818 * @param pipe_stdout pipe to use to get output from child process (or NULL)
819 * @param filename name of the binary
820 * @param ... NULL-terminated list of arguments to the process
822 * @return pointer to process structure of the new process, NULL on error
825 struct GNUNET_OS_Process *
826 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
827 struct GNUNET_DISK_PipeHandle *pipe_stdout,
828 const char *filename, ...)
830 struct GNUNET_OS_Process *ret;
833 va_start (ap, filename);
834 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
843 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
844 * must be NULL on platforms where dup is not supported
845 * @param filename name of the binary
846 * @param argv NULL-terminated list of arguments to the process
847 * @return process ID of the new process, -1 on error
849 struct GNUNET_OS_Process *
850 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
853 #if ENABLE_WINDOWS_WORKAROUNDS
854 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
855 char *childpipename = NULL;
862 struct GNUNET_OS_Process *gnunet_proc = NULL;
871 #if ENABLE_WINDOWS_WORKAROUNDS
873 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
874 GNUNET_DISK_PERM_USER_READ |
875 GNUNET_DISK_PERM_USER_WRITE);
876 if (control_pipe == NULL)
885 while (-1 != (k = lsocks[i++]))
886 GNUNET_array_append (lscp, ls, k);
887 GNUNET_array_append (lscp, ls, -1);
894 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
895 #if ENABLE_WINDOWS_WORKAROUNDS
896 GNUNET_DISK_npipe_close (control_pipe);
901 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
902 gnunet_proc->pid = ret;
903 #if ENABLE_WINDOWS_WORKAROUNDS
904 gnunet_proc->control_pipe = control_pipe;
908 GNUNET_array_grow (lscp, ls, 0);
909 #if ENABLE_WINDOWS_WORKAROUNDS
910 GNUNET_free (childpipename);
915 #if ENABLE_WINDOWS_WORKAROUNDS
916 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
917 GNUNET_free (childpipename);
922 /* read systemd documentation... */
923 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
924 setenv ("LISTEN_PID", lpid, 1);
927 while (-1 != lscp[i])
930 while (-1 != lscp[j])
936 GNUNET_assert (-1 != k);
937 GNUNET_assert (0 == close (lscp[j]));
945 /* Bury any existing FD, no matter what; they should all be closed
946 * on exec anyway and the important onces have been dup'ed away */
948 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
950 /* unset close-on-exec flag */
951 flags = fcntl (tgt, F_GETFD);
952 GNUNET_assert (flags >= 0);
953 flags &= ~FD_CLOEXEC;
955 (void) fcntl (tgt, F_SETFD, flags);
959 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
960 setenv ("LISTEN_FDS", fds, 1);
962 GNUNET_array_grow (lscp, ls, 0);
963 execvp (filename, argv);
964 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
967 char **arg, **non_const_argv;
971 PROCESS_INFORMATION proc;
973 struct GNUNET_OS_Process *gnunet_proc = NULL;
975 char path[MAX_PATH + 1];
977 char *our_env[3] = { NULL, NULL, NULL };
978 char *env_block = NULL;
980 DWORD pathbuf_len, alloc_len;
985 char *non_const_filename;
987 GNUNET_assert (lsocks == NULL);
989 /* Search in prefix dir (hopefully - the directory from which
990 * the current module was loaded), bindir and libdir, then in PATH
992 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
993 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
994 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
996 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
999 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1002 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1005 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1006 GNUNET_free (self_prefix);
1007 GNUNET_free (bindir);
1008 GNUNET_free (libdir);
1010 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1011 if (alloc_len != pathbuf_len - 1)
1013 GNUNET_free (pathbuf);
1014 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1018 cmdlen = strlen (filename);
1019 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1020 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1022 GNUNET_asprintf (&non_const_filename, "%s", filename);
1024 /* Check that this is the full path. If it isn't, search. */
1025 if (non_const_filename[1] == ':')
1026 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1027 else if (!SearchPathA
1028 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1031 SetErrnoFromWinError (GetLastError ());
1032 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1033 non_const_filename);
1034 GNUNET_free (non_const_filename);
1035 GNUNET_free (pathbuf);
1038 GNUNET_free (pathbuf);
1039 GNUNET_free (non_const_filename);
1041 /* Count the number of arguments */
1042 arg = (char **) argv;
1049 /* Allocate a copy argv */
1050 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1052 /* Copy all argv strings */
1054 arg = (char **) argv;
1058 non_const_argv[argcount] = GNUNET_strdup (path);
1060 non_const_argv[argcount] = GNUNET_strdup (*arg);
1064 non_const_argv[argcount] = NULL;
1068 arg = non_const_argv;
1071 cmdlen = cmdlen + strlen (*arg) + 3;
1075 /* Allocate and create cmd */
1076 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1077 arg = non_const_argv;
1080 idx += sprintf (idx, "\"%s\" ", *arg);
1084 while (argcount > 0)
1085 GNUNET_free (non_const_argv[--argcount]);
1086 GNUNET_free (non_const_argv);
1088 memset (&start, 0, sizeof (start));
1089 start.cb = sizeof (start);
1092 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1093 GNUNET_DISK_PERM_USER_READ |
1094 GNUNET_DISK_PERM_USER_WRITE);
1095 if (control_pipe == NULL)
1103 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1107 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1108 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1110 env_block = CreateCustomEnvTable (our_env);
1111 GNUNET_free (our_env[0]);
1112 GNUNET_free (our_env[1]);
1115 (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1116 env_block, NULL, &start, &proc))
1118 SetErrnoFromWinError (GetLastError ());
1119 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1120 GNUNET_free (env_block);
1125 GNUNET_free (env_block);
1127 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1128 gnunet_proc->pid = proc.dwProcessId;
1129 gnunet_proc->handle = proc.hProcess;
1130 gnunet_proc->control_pipe = control_pipe;
1132 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1134 ResumeThread (proc.hThread);
1135 CloseHandle (proc.hThread);
1144 * Retrieve the status of a process
1145 * @param proc process ID
1146 * @param type status type
1147 * @param code return code/signal number
1148 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1151 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1152 enum GNUNET_OS_ProcessStatusType *type,
1153 unsigned long *code)
1159 GNUNET_assert (0 != proc);
1160 ret = waitpid (proc->pid, &status, WNOHANG);
1163 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1164 return GNUNET_SYSERR;
1168 *type = GNUNET_OS_PROCESS_RUNNING;
1172 if (proc->pid != ret)
1174 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1175 return GNUNET_SYSERR;
1177 if (WIFEXITED (status))
1179 *type = GNUNET_OS_PROCESS_EXITED;
1180 *code = WEXITSTATUS (status);
1182 else if (WIFSIGNALED (status))
1184 *type = GNUNET_OS_PROCESS_SIGNALED;
1185 *code = WTERMSIG (status);
1187 else if (WIFSTOPPED (status))
1189 *type = GNUNET_OS_PROCESS_SIGNALED;
1190 *code = WSTOPSIG (status);
1193 else if (WIFCONTINUED (status))
1195 *type = GNUNET_OS_PROCESS_RUNNING;
1201 *type = GNUNET_OS_PROCESS_UNKNOWN;
1206 DWORD c, error_code, ret;
1210 if (h == NULL || ret == 0)
1212 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1214 return GNUNET_SYSERR;
1217 h = GetCurrentProcess ();
1220 ret = GetExitCodeProcess (h, &c);
1221 error_code = GetLastError ();
1222 if (ret == 0 || error_code != NO_ERROR)
1224 SetErrnoFromWinError (error_code);
1225 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1226 return GNUNET_SYSERR;
1228 if (STILL_ACTIVE == c)
1230 *type = GNUNET_OS_PROCESS_RUNNING;
1234 *type = GNUNET_OS_PROCESS_EXITED;
1243 * Wait for a process
1244 * @param proc pointer to process structure
1245 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1248 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1252 pid_t pid = proc->pid;
1254 if (pid != waitpid (pid, NULL, 0))
1255 return GNUNET_SYSERR;
1264 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1266 return GNUNET_SYSERR;
1269 h = GetCurrentProcess ();
1271 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1273 SetErrnoFromWinError (GetLastError ());
1274 ret = GNUNET_SYSERR;
1285 * Handle to a command.
1287 struct GNUNET_OS_CommandHandle
1293 struct GNUNET_OS_Process *eip;
1296 * Handle to the output pipe.
1298 struct GNUNET_DISK_PipeHandle *opipe;
1301 * Read-end of output pipe.
1303 const struct GNUNET_DISK_FileHandle *r;
1306 * Function to call on each line of output.
1308 GNUNET_OS_LineProcessor proc;
1311 * Closure for 'proc'.
1316 * Buffer for the output.
1321 * Task reading from pipe.
1323 GNUNET_SCHEDULER_TaskIdentifier rtask;
1328 struct GNUNET_TIME_Absolute timeout;
1331 * Current read offset in buf.
1338 * Stop/kill a command. Must ONLY be called either from
1339 * the callback after 'NULL' was passed for 'line' *OR*
1340 * from an independent task (not within the line processor).
1342 * @param cmd handle to the process
1345 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1348 if (cmd->proc != NULL)
1350 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1351 GNUNET_SCHEDULER_cancel (cmd->rtask);
1353 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1354 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1355 GNUNET_OS_process_close (cmd->eip);
1356 GNUNET_DISK_pipe_close (cmd->opipe);
1362 * Read from the process and call the line processor.
1364 * @param cls the 'struct GNUNET_OS_CommandHandle'
1365 * @param tc scheduler context
1368 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1370 struct GNUNET_OS_CommandHandle *cmd = cls;
1371 GNUNET_OS_LineProcessor proc;
1375 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1376 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1378 /* timeout, shutdown, etc. */
1381 proc (cmd->proc_cls, NULL);
1385 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1386 sizeof (cmd->buf) - cmd->off);
1389 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1391 cmd->buf[cmd->off] = '\0';
1392 cmd->proc (cmd->proc_cls, cmd->buf);
1396 proc (cmd->proc_cls, NULL);
1399 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1404 cmd->proc (cmd->proc_cls, cmd->buf);
1405 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1406 cmd->off -= (end + 1 - cmd->buf);
1407 end = memchr (cmd->buf, '\n', cmd->off);
1410 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1411 (cmd->timeout), cmd->r, &cmd_read, cmd);
1416 * Run the given command line and call the given function
1417 * for each line of the output.
1419 * @param proc function to call for each line of the output
1420 * @param proc_cls closure for proc
1421 * @param timeout when to time out
1422 * @param binary command to run
1423 * @param ... arguments to command
1424 * @return NULL on error
1426 struct GNUNET_OS_CommandHandle *
1427 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1428 struct GNUNET_TIME_Relative timeout, const char *binary,
1431 struct GNUNET_OS_CommandHandle *cmd;
1432 struct GNUNET_OS_Process *eip;
1433 struct GNUNET_DISK_PipeHandle *opipe;
1436 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1439 va_start (ap, binary);
1440 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1444 GNUNET_DISK_pipe_close (opipe);
1447 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1448 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1449 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1453 cmd->proc_cls = proc_cls;
1454 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1455 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1462 /* end of os_priority.c */