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 #define DEBUG_OS GNUNET_EXTRA_LOGGING
43 struct GNUNET_OS_Process
50 struct GNUNET_DISK_FileHandle *control_pipe;
53 static struct GNUNET_OS_Process current_process;
57 * This handler is called when there are control data to be read on the pipe
59 * @param cls the 'struct GNUNET_DISK_FileHandle' of the control pipe
60 * @param tc scheduler context
63 parent_control_handler (void *cls,
64 const struct GNUNET_SCHEDULER_TaskContext *tc)
66 struct GNUNET_DISK_FileHandle *control_pipe =
67 (struct GNUNET_DISK_FileHandle *) cls;
71 LOG (GNUNET_ERROR_TYPE_DEBUG, "`%s' invoked because of %d\n", __FUNCTION__,
75 (GNUNET_SCHEDULER_REASON_SHUTDOWN | GNUNET_SCHEDULER_REASON_TIMEOUT |
76 GNUNET_SCHEDULER_REASON_PREREQ_DONE))
78 GNUNET_DISK_npipe_close (control_pipe);
82 if (GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)) !=
85 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
86 GNUNET_DISK_npipe_close (control_pipe);
91 LOG (GNUNET_ERROR_TYPE_DEBUG, "Got control code %d from parent\n", sig);
93 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
94 control_pipe, &parent_control_handler,
103 * Task that connects this process to its parent via pipe
106 GNUNET_OS_install_parent_control_handler (void *cls,
108 GNUNET_SCHEDULER_TaskContext *tc)
111 struct GNUNET_DISK_FileHandle *control_pipe;
113 env_buf = getenv (GNUNET_OS_CONTROL_PIPE);
114 if ((env_buf == NULL) || (strlen (env_buf) <= 0))
116 LOG (GNUNET_ERROR_TYPE_INFO, _("Not installing a handler because $%s=%s\n"),
117 GNUNET_OS_CONTROL_PIPE, env_buf);
118 putenv ("GNUNET_OS_CONTROL_PIPE=");
122 GNUNET_DISK_npipe_open (env_buf, GNUNET_DISK_OPEN_READ,
123 GNUNET_DISK_PERM_USER_READ |
124 GNUNET_DISK_PERM_USER_WRITE);
125 if (control_pipe == NULL)
127 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
128 putenv ("GNUNET_OS_CONTROL_PIPE=");
132 LOG (GNUNET_ERROR_TYPE_DEBUG,
133 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
135 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
136 &parent_control_handler, control_pipe);
137 putenv ("GNUNET_OS_CONTROL_PIPE=");
142 * Get process structure for current process
144 * The pointer it returns points to static memory location and must not be
147 * @return pointer to the process sturcutre for this process
149 struct GNUNET_OS_Process *
150 GNUNET_OS_process_current ()
153 current_process.pid = GetCurrentProcessId ();
154 current_process.handle = GetCurrentProcess ();
156 current_process.pid = 0;
158 return ¤t_process;
163 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
165 #if ENABLE_WINDOWS_WORKAROUNDS
169 ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
170 if (ret != sizeof (sig))
174 /* Child process is not controllable via pipe */
176 LOG (GNUNET_ERROR_TYPE_DEBUG,
177 "Child process is not controllable, will kill it directly\n");
180 else if (errno == EPIPE)
183 LOG (GNUNET_ERROR_TYPE_DEBUG,
184 "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
188 LOG (GNUNET_ERROR_TYPE_WARNING,
189 "Failed to write into control pipe , errno is %d\n", errno);
190 #if WINDOWS && !defined(__CYGWIN__)
191 TerminateProcess (proc->handle, 0);
193 PLIBC_KILL (proc->pid, sig);
199 LOG (GNUNET_ERROR_TYPE_DEBUG,
200 "Wrote control code into control pipe, now waiting\n");
204 /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
205 if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
206 TerminateProcess (proc->handle, 0);
209 struct GNUNET_NETWORK_FDSet *rfds;
210 struct GNUNET_NETWORK_FDSet *efds;
212 rfds = GNUNET_NETWORK_fdset_create ();
213 efds = GNUNET_NETWORK_fdset_create ();
215 GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
216 GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
218 /* Ndurner thought this up, and i have no idea what it does.
219 * There's have never been any code to answer the shutdown call
220 * (write a single int into the pipe, so that this function can read it).
221 * On *nix select() will probably tell that pipe is ready
222 * for reading, once the other process shuts down,
223 * but the read () call will fail, triggering a kill ()
224 * on the pid that is already dead. This will probably result in non-0
225 * return from kill(), and therefore from this function.
230 GNUNET_NETWORK_socket_select (rfds, NULL, efds,
231 GNUNET_TIME_relative_multiply
232 (GNUNET_TIME_relative_get_unit (),
236 GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
238 /* Just to be sure */
239 PLIBC_KILL (proc->pid, sig);
245 if (GNUNET_DISK_file_read (proc->control_pipe, &ret, sizeof (ret)) !=
247 res = PLIBC_KILL (proc->pid, sig);
249 /* Child signaled shutdown is in progress */
258 return kill (proc->pid, sig);
263 * Get the pid of the process in question
265 * @param proc the process to get the pid of
267 * @return the current process id
270 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
277 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
279 #if ENABLE_WINDOWS_WORKAROUNDS
280 if (proc->control_pipe)
281 GNUNET_DISK_npipe_close (proc->control_pipe);
285 if (proc->handle != NULL)
286 CloseHandle (proc->handle);
293 #include "gnunet_signal_lib.h"
295 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
298 * Make seaspider happy.
300 #define DWORD_WINAPI DWORD WINAPI
303 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
304 * @param proc pointer to process structure
307 ChildWaitThread (void *arg)
309 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
311 WaitForSingleObject (proc->handle, INFINITE);
313 if (w32_sigchld_handler)
314 w32_sigchld_handler ();
321 * Set process priority
323 * @param proc pointer to process structure
324 * @param prio priority value
325 * @return GNUNET_OK on success, GNUNET_SYSERR on error
328 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
329 enum GNUNET_SCHEDULER_Priority prio)
333 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
334 if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
337 /* convert to MINGW/Unix values */
340 case GNUNET_SCHEDULER_PRIORITY_UI:
341 case GNUNET_SCHEDULER_PRIORITY_URGENT:
343 rprio = HIGH_PRIORITY_CLASS;
349 case GNUNET_SCHEDULER_PRIORITY_HIGH:
351 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
357 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
359 rprio = NORMAL_PRIORITY_CLASS;
365 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
367 rprio = BELOW_NORMAL_PRIORITY_CLASS;
373 case GNUNET_SCHEDULER_PRIORITY_IDLE:
375 rprio = IDLE_PRIORITY_CLASS;
382 return GNUNET_SYSERR;
385 /* Set process priority */
388 HANDLE h = proc->handle;
390 GNUNET_assert (h != NULL);
391 SetPriorityClass (h, rprio);
397 if ((0 == pid) || (pid == getpid ()))
400 int delta = rprio - have;
403 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
405 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, "nice");
406 return GNUNET_SYSERR;
411 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
413 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
415 return GNUNET_SYSERR;
420 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
421 "Priority management not availabe for this platform\n");
429 CreateCustomEnvTable (char **vars)
431 char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
432 size_t tablesize = 0;
433 size_t items_count = 0;
434 size_t n_found = 0, n_var;
441 win32_env_table = GetEnvironmentStringsA ();
442 if (win32_env_table == NULL)
444 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) ;
446 index = GNUNET_malloc (sizeof (char *) * n_var);
447 for (c = 0; c < n_var; c++)
449 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
451 size_t len = strlen (ptr);
454 for (var_ptr = vars; *var_ptr; var_ptr++)
458 var_len = strlen (var);
459 if (strncmp (var, ptr, var_len) == 0)
463 tablesize += var_len + strlen (val) + 1;
468 tablesize += len + 1;
471 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
476 n_found += strlen (var) + strlen (val) + 1;
478 result = GNUNET_malloc (tablesize + n_found + 1);
479 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
481 size_t len = strlen (ptr);
484 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
488 var_len = strlen (var);
489 if (strncmp (var, ptr, var_len) == 0)
497 strcpy (result_ptr, ptr);
498 result_ptr += len + 1;
502 strcpy (result_ptr, var);
503 result_ptr += var_len;
504 strcpy (result_ptr, val);
505 result_ptr += strlen (val) + 1;
509 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
513 var_len = strlen (var);
516 strcpy (result_ptr, var);
517 result_ptr += var_len;
518 strcpy (result_ptr, val);
519 result_ptr += strlen (val) + 1;
522 FreeEnvironmentStrings (win32_env_table);
533 * @param pipe_stdin pipe to use to send input to child process (or NULL)
534 * @param pipe_stdout pipe to use to get output from child process (or NULL)
535 * @param filename name of the binary
536 * @param va NULL-terminated list of arguments to the process
537 * @return pointer to process structure of the new process, NULL on error
539 struct GNUNET_OS_Process *
540 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
541 struct GNUNET_DISK_PipeHandle *pipe_stdout,
542 const char *filename, va_list va)
546 #if ENABLE_WINDOWS_WORKAROUNDS
547 char *childpipename = NULL;
548 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
550 struct GNUNET_OS_Process *gnunet_proc = NULL;
561 #if ENABLE_WINDOWS_WORKAROUNDS
563 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
564 GNUNET_DISK_PERM_USER_READ |
565 GNUNET_DISK_PERM_USER_WRITE);
566 if (control_pipe == NULL)
572 while (NULL != va_arg (ap, char *))
576 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
579 while (NULL != (argv[argc] = va_arg (ap, char *)))
583 if (pipe_stdout != NULL)
585 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
587 GNUNET_DISK_PIPE_END_WRITE),
588 &fd_stdout_write, sizeof (int));
589 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
590 (pipe_stdout, GNUNET_DISK_PIPE_END_READ),
591 &fd_stdout_read, sizeof (int));
593 if (pipe_stdin != NULL)
595 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
596 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
597 &fd_stdin_read, sizeof (int));
598 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
599 (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
600 &fd_stdin_write, sizeof (int));
608 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
609 #if ENABLE_WINDOWS_WORKAROUNDS
610 GNUNET_DISK_npipe_close (control_pipe);
615 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
616 gnunet_proc->pid = ret;
617 #if ENABLE_WINDOWS_WORKAROUNDS
618 gnunet_proc->control_pipe = control_pipe;
622 #if ENABLE_WINDOWS_WORKAROUNDS
623 GNUNET_free (childpipename);
628 #if ENABLE_WINDOWS_WORKAROUNDS
629 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
630 GNUNET_free (childpipename);
633 if (pipe_stdout != NULL)
635 GNUNET_break (0 == close (fd_stdout_read));
636 if (-1 == dup2 (fd_stdout_write, 1))
637 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
638 GNUNET_break (0 == close (fd_stdout_write));
641 if (pipe_stdin != NULL)
644 GNUNET_break (0 == close (fd_stdin_write));
645 if (-1 == dup2 (fd_stdin_read, 0))
646 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
647 GNUNET_break (0 == close (fd_stdin_read));
649 execvp (filename, argv);
650 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
657 PROCESS_INFORMATION proc;
660 HANDLE stdout_handle;
662 char path[MAX_PATH + 1];
664 char *our_env[3] = { NULL, NULL, NULL };
665 char *env_block = NULL;
667 DWORD pathbuf_len, alloc_len;
672 char *non_const_filename;
674 /* Search in prefix dir (hopefully - the directory from which
675 * the current module was loaded), bindir and libdir, then in PATH
677 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
678 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
679 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
681 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
684 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
687 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
690 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
691 GNUNET_free (self_prefix);
692 GNUNET_free (bindir);
693 GNUNET_free (libdir);
695 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
696 GNUNET_assert (alloc_len == (pathbuf_len - 1));
698 cmdlen = strlen (filename);
699 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
700 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
702 GNUNET_asprintf (&non_const_filename, "%s", filename);
704 /* Check that this is the full path. If it isn't, search. */
705 if (non_const_filename[1] == ':')
706 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
707 else if (!SearchPathA
708 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
711 SetErrnoFromWinError (GetLastError ());
712 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
714 GNUNET_free (non_const_filename);
715 GNUNET_free (pathbuf);
718 GNUNET_free (pathbuf);
719 GNUNET_free (non_const_filename);
723 while (NULL != (arg = va_arg (ap, char *)))
726 cmdlen = cmdlen + strlen (path) + 3;
728 cmdlen = cmdlen + strlen (arg) + 3;
732 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
734 while (NULL != (arg = va_arg (ap, char *)))
737 idx += sprintf (idx, "\"%s\" ", path);
739 idx += sprintf (idx, "\"%s\" ", arg);
743 memset (&start, 0, sizeof (start));
744 start.cb = sizeof (start);
746 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
747 start.dwFlags |= STARTF_USESTDHANDLES;
749 if (pipe_stdin != NULL)
751 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
752 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
753 &stdin_handle, sizeof (HANDLE));
754 start.hStdInput = stdin_handle;
757 if (pipe_stdout != NULL)
759 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
761 GNUNET_DISK_PIPE_END_WRITE),
762 &stdout_handle, sizeof (HANDLE));
763 start.hStdOutput = stdout_handle;
767 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
768 GNUNET_DISK_PERM_USER_READ |
769 GNUNET_DISK_PERM_USER_WRITE);
770 if (control_pipe == NULL)
778 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
782 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
783 GNUNET_asprintf (&our_env[1], "%s", childpipename);
785 env_block = CreateCustomEnvTable (our_env);
786 GNUNET_free (our_env[0]);
787 GNUNET_free (our_env[1]);
790 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
791 env_block, NULL, &start, &proc))
793 SetErrnoFromWinError (GetLastError ());
794 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
795 GNUNET_free (env_block);
800 GNUNET_free (env_block);
802 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
803 gnunet_proc->pid = proc.dwProcessId;
804 gnunet_proc->handle = proc.hProcess;
805 gnunet_proc->control_pipe = control_pipe;
807 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
809 ResumeThread (proc.hThread);
810 CloseHandle (proc.hThread);
822 * @param pipe_stdin pipe to use to send input to child process (or NULL)
823 * @param pipe_stdout pipe to use to get output from child process (or NULL)
824 * @param filename name of the binary
825 * @param ... NULL-terminated list of arguments to the process
827 * @return pointer to process structure of the new process, NULL on error
830 struct GNUNET_OS_Process *
831 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
832 struct GNUNET_DISK_PipeHandle *pipe_stdout,
833 const char *filename, ...)
835 struct GNUNET_OS_Process *ret;
838 va_start (ap, filename);
839 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
848 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
849 * must be NULL on platforms where dup is not supported
850 * @param filename name of the binary
851 * @param argv NULL-terminated list of arguments to the process
852 * @return process ID of the new process, -1 on error
854 struct GNUNET_OS_Process *
855 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
858 #if ENABLE_WINDOWS_WORKAROUNDS
859 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
860 char *childpipename = NULL;
867 struct GNUNET_OS_Process *gnunet_proc = NULL;
876 #if ENABLE_WINDOWS_WORKAROUNDS
878 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
879 GNUNET_DISK_PERM_USER_READ |
880 GNUNET_DISK_PERM_USER_WRITE);
881 if (control_pipe == NULL)
890 while (-1 != (k = lsocks[i++]))
891 GNUNET_array_append (lscp, ls, k);
892 GNUNET_array_append (lscp, ls, -1);
899 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
900 #if ENABLE_WINDOWS_WORKAROUNDS
901 GNUNET_DISK_npipe_close (control_pipe);
906 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
907 gnunet_proc->pid = ret;
908 #if ENABLE_WINDOWS_WORKAROUNDS
909 gnunet_proc->control_pipe = control_pipe;
913 GNUNET_array_grow (lscp, ls, 0);
914 #if ENABLE_WINDOWS_WORKAROUNDS
915 GNUNET_free (childpipename);
920 #if ENABLE_WINDOWS_WORKAROUNDS
921 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
922 GNUNET_free (childpipename);
927 /* read systemd documentation... */
928 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
929 setenv ("LISTEN_PID", lpid, 1);
932 while (-1 != lscp[i])
935 while (-1 != lscp[j])
941 GNUNET_assert (-1 != k);
942 GNUNET_assert (0 == close (lscp[j]));
950 /* Bury any existing FD, no matter what; they should all be closed
951 * on exec anyway and the important onces have been dup'ed away */
953 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
955 /* unset close-on-exec flag */
956 flags = fcntl (tgt, F_GETFD);
957 GNUNET_assert (flags >= 0);
958 flags &= ~FD_CLOEXEC;
960 (void) fcntl (tgt, F_SETFD, flags);
964 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
965 setenv ("LISTEN_FDS", fds, 1);
967 GNUNET_array_grow (lscp, ls, 0);
968 execvp (filename, argv);
969 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
972 char **arg, **non_const_argv;
976 PROCESS_INFORMATION proc;
978 struct GNUNET_OS_Process *gnunet_proc = NULL;
980 char path[MAX_PATH + 1];
982 char *our_env[3] = { NULL, NULL, NULL };
983 char *env_block = NULL;
985 DWORD pathbuf_len, alloc_len;
990 char *non_const_filename;
992 GNUNET_assert (lsocks == NULL);
994 /* Search in prefix dir (hopefully - the directory from which
995 * the current module was loaded), bindir and libdir, then in PATH
997 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
998 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
999 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1001 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1004 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1007 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1010 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1011 GNUNET_free (self_prefix);
1012 GNUNET_free (bindir);
1013 GNUNET_free (libdir);
1015 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1016 if (alloc_len != pathbuf_len - 1)
1018 GNUNET_free (pathbuf);
1019 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1023 cmdlen = strlen (filename);
1024 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1025 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1027 GNUNET_asprintf (&non_const_filename, "%s", filename);
1029 /* Check that this is the full path. If it isn't, search. */
1030 if (non_const_filename[1] == ':')
1031 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1032 else if (!SearchPathA
1033 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1036 SetErrnoFromWinError (GetLastError ());
1037 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1038 non_const_filename);
1039 GNUNET_free (non_const_filename);
1040 GNUNET_free (pathbuf);
1043 GNUNET_free (pathbuf);
1044 GNUNET_free (non_const_filename);
1046 /* Count the number of arguments */
1047 arg = (char **) argv;
1054 /* Allocate a copy argv */
1055 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1057 /* Copy all argv strings */
1059 arg = (char **) argv;
1063 non_const_argv[argcount] = GNUNET_strdup (path);
1065 non_const_argv[argcount] = GNUNET_strdup (*arg);
1069 non_const_argv[argcount] = NULL;
1073 arg = non_const_argv;
1076 cmdlen = cmdlen + strlen (*arg) + 3;
1080 /* Allocate and create cmd */
1081 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1082 arg = non_const_argv;
1085 idx += sprintf (idx, "\"%s\" ", *arg);
1089 while (argcount > 0)
1090 GNUNET_free (non_const_argv[--argcount]);
1091 GNUNET_free (non_const_argv);
1093 memset (&start, 0, sizeof (start));
1094 start.cb = sizeof (start);
1097 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1098 GNUNET_DISK_PERM_USER_READ |
1099 GNUNET_DISK_PERM_USER_WRITE);
1100 if (control_pipe == NULL)
1108 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1112 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1113 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1115 env_block = CreateCustomEnvTable (our_env);
1116 GNUNET_free (our_env[0]);
1117 GNUNET_free (our_env[1]);
1120 (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1121 env_block, NULL, &start, &proc))
1123 SetErrnoFromWinError (GetLastError ());
1124 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1125 GNUNET_free (env_block);
1130 GNUNET_free (env_block);
1132 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1133 gnunet_proc->pid = proc.dwProcessId;
1134 gnunet_proc->handle = proc.hProcess;
1135 gnunet_proc->control_pipe = control_pipe;
1137 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1139 ResumeThread (proc.hThread);
1140 CloseHandle (proc.hThread);
1149 * Retrieve the status of a process
1150 * @param proc process ID
1151 * @param type status type
1152 * @param code return code/signal number
1153 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1156 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1157 enum GNUNET_OS_ProcessStatusType *type,
1158 unsigned long *code)
1164 GNUNET_assert (0 != proc);
1165 ret = waitpid (proc->pid, &status, WNOHANG);
1168 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1169 return GNUNET_SYSERR;
1173 *type = GNUNET_OS_PROCESS_RUNNING;
1177 if (proc->pid != ret)
1179 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1180 return GNUNET_SYSERR;
1182 if (WIFEXITED (status))
1184 *type = GNUNET_OS_PROCESS_EXITED;
1185 *code = WEXITSTATUS (status);
1187 else if (WIFSIGNALED (status))
1189 *type = GNUNET_OS_PROCESS_SIGNALED;
1190 *code = WTERMSIG (status);
1192 else if (WIFSTOPPED (status))
1194 *type = GNUNET_OS_PROCESS_SIGNALED;
1195 *code = WSTOPSIG (status);
1198 else if (WIFCONTINUED (status))
1200 *type = GNUNET_OS_PROCESS_RUNNING;
1206 *type = GNUNET_OS_PROCESS_UNKNOWN;
1211 DWORD c, error_code, ret;
1215 if (h == NULL || ret == 0)
1217 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1219 return GNUNET_SYSERR;
1222 h = GetCurrentProcess ();
1225 ret = GetExitCodeProcess (h, &c);
1226 error_code = GetLastError ();
1227 if (ret == 0 || error_code != NO_ERROR)
1229 SetErrnoFromWinError (error_code);
1230 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1231 return GNUNET_SYSERR;
1233 if (STILL_ACTIVE == c)
1235 *type = GNUNET_OS_PROCESS_RUNNING;
1239 *type = GNUNET_OS_PROCESS_EXITED;
1248 * Wait for a process
1249 * @param proc pointer to process structure
1250 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1253 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1257 pid_t pid = proc->pid;
1259 if (pid != waitpid (pid, NULL, 0))
1260 return GNUNET_SYSERR;
1269 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1271 return GNUNET_SYSERR;
1274 h = GetCurrentProcess ();
1276 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1278 SetErrnoFromWinError (GetLastError ());
1279 ret = GNUNET_SYSERR;
1290 * Handle to a command.
1292 struct GNUNET_OS_CommandHandle
1298 struct GNUNET_OS_Process *eip;
1301 * Handle to the output pipe.
1303 struct GNUNET_DISK_PipeHandle *opipe;
1306 * Read-end of output pipe.
1308 const struct GNUNET_DISK_FileHandle *r;
1311 * Function to call on each line of output.
1313 GNUNET_OS_LineProcessor proc;
1316 * Closure for 'proc'.
1321 * Buffer for the output.
1326 * Task reading from pipe.
1328 GNUNET_SCHEDULER_TaskIdentifier rtask;
1333 struct GNUNET_TIME_Absolute timeout;
1336 * Current read offset in buf.
1343 * Stop/kill a command. Must ONLY be called either from
1344 * the callback after 'NULL' was passed for 'line' *OR*
1345 * from an independent task (not within the line processor).
1347 * @param cmd handle to the process
1350 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1353 if (cmd->proc != NULL)
1355 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1356 GNUNET_SCHEDULER_cancel (cmd->rtask);
1358 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1359 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1360 GNUNET_OS_process_close (cmd->eip);
1361 GNUNET_DISK_pipe_close (cmd->opipe);
1367 * Read from the process and call the line processor.
1369 * @param cls the 'struct GNUNET_OS_CommandHandle'
1370 * @param tc scheduler context
1373 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1375 struct GNUNET_OS_CommandHandle *cmd = cls;
1376 GNUNET_OS_LineProcessor proc;
1380 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1381 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1383 /* timeout, shutdown, etc. */
1386 proc (cmd->proc_cls, NULL);
1390 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1391 sizeof (cmd->buf) - cmd->off);
1394 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1396 cmd->buf[cmd->off] = '\0';
1397 cmd->proc (cmd->proc_cls, cmd->buf);
1401 proc (cmd->proc_cls, NULL);
1404 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1409 cmd->proc (cmd->proc_cls, cmd->buf);
1410 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1411 cmd->off -= (end + 1 - cmd->buf);
1412 end = memchr (cmd->buf, '\n', cmd->off);
1415 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1416 (cmd->timeout), cmd->r, &cmd_read, cmd);
1421 * Run the given command line and call the given function
1422 * for each line of the output.
1424 * @param proc function to call for each line of the output
1425 * @param proc_cls closure for proc
1426 * @param timeout when to time out
1427 * @param binary command to run
1428 * @param ... arguments to command
1429 * @return NULL on error
1431 struct GNUNET_OS_CommandHandle *
1432 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1433 struct GNUNET_TIME_Relative timeout, const char *binary,
1436 struct GNUNET_OS_CommandHandle *cmd;
1437 struct GNUNET_OS_Process *eip;
1438 struct GNUNET_DISK_PipeHandle *opipe;
1441 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1444 va_start (ap, binary);
1445 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1449 GNUNET_DISK_pipe_close (opipe);
1452 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1453 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1454 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1458 cmd->proc_cls = proc_cls;
1459 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1460 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1467 /* end of os_priority.c */