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",
70 __FUNCTION__, tc->reason);
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",
92 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
94 &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,
117 _("Not installing a handler because $%s=%s\n"),
118 GNUNET_OS_CONTROL_PIPE, env_buf);
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);
131 LOG (GNUNET_ERROR_TYPE_DEBUG,
132 "Adding parent control handler pipe `%s' to the scheduler\n", env_buf);
134 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, control_pipe,
135 &parent_control_handler, control_pipe);
140 * Get process structure for current process
142 * The pointer it returns points to static memory location and must not be
145 * @return pointer to the process sturcutre for this process
147 struct GNUNET_OS_Process *
148 GNUNET_OS_process_current ()
151 current_process.pid = GetCurrentProcessId ();
152 current_process.handle = GetCurrentProcess ();
154 current_process.pid = 0;
156 return ¤t_process;
161 GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
163 #if ENABLE_WINDOWS_WORKAROUNDS
167 ret = GNUNET_DISK_file_write (proc->control_pipe, &sig, sizeof (sig));
168 if (ret != sizeof (sig))
172 /* Child process is not controllable via pipe */
174 LOG (GNUNET_ERROR_TYPE_DEBUG,
175 "Child process is not controllable, will kill it directly\n");
178 else if (errno == EPIPE)
181 LOG (GNUNET_ERROR_TYPE_DEBUG,
182 "Failed to write into control pipe, because pipe is invalid (the child is most likely dead)\n");
186 LOG (GNUNET_ERROR_TYPE_WARNING,
187 "Failed to write into control pipe , errno is %d\n", errno);
188 #if WINDOWS && !defined(__CYGWIN__)
189 TerminateProcess (proc->handle, 0);
191 PLIBC_KILL (proc->pid, sig);
197 LOG (GNUNET_ERROR_TYPE_DEBUG,
198 "Wrote control code into control pipe, now waiting\n");
202 /* Give it 3 seconds to die, then kill it in a nice Windows-specific way */
203 if (WaitForSingleObject (proc->handle, 3000) != WAIT_OBJECT_0)
204 TerminateProcess (proc->handle, 0);
207 struct GNUNET_NETWORK_FDSet *rfds;
208 struct GNUNET_NETWORK_FDSet *efds;
210 rfds = GNUNET_NETWORK_fdset_create ();
211 efds = GNUNET_NETWORK_fdset_create ();
213 GNUNET_NETWORK_fdset_handle_set (rfds, proc->control_pipe);
214 GNUNET_NETWORK_fdset_handle_set (efds, proc->control_pipe);
216 /* Ndurner thought this up, and i have no idea what it does.
217 * There's have never been any code to answer the shutdown call
218 * (write a single int into the pipe, so that this function can read it).
219 * On *nix select() will probably tell that pipe is ready
220 * for reading, once the other process shuts down,
221 * but the read () call will fail, triggering a kill ()
222 * on the pid that is already dead. This will probably result in non-0
223 * return from kill(), and therefore from this function.
228 GNUNET_NETWORK_socket_select (rfds, NULL, efds,
229 GNUNET_TIME_relative_multiply
230 (GNUNET_TIME_relative_get_unit (),
234 GNUNET_NETWORK_fdset_handle_isset (efds, proc->control_pipe))
236 /* Just to be sure */
237 PLIBC_KILL (proc->pid, sig);
243 if (GNUNET_DISK_file_read
244 (proc->control_pipe, &ret, sizeof (ret)) != GNUNET_OK)
245 res = PLIBC_KILL (proc->pid, sig);
247 /* Child signaled shutdown is in progress */
256 return kill (proc->pid, sig);
261 * Get the pid of the process in question
263 * @param proc the process to get the pid of
265 * @return the current process id
268 GNUNET_OS_process_get_pid (struct GNUNET_OS_Process * proc)
275 GNUNET_OS_process_close (struct GNUNET_OS_Process *proc)
277 #if ENABLE_WINDOWS_WORKAROUNDS
278 if (proc->control_pipe)
279 GNUNET_DISK_npipe_close (proc->control_pipe);
283 if (proc->handle != NULL)
284 CloseHandle (proc->handle);
291 #include "gnunet_signal_lib.h"
293 extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
296 * Make seaspider happy.
298 #define DWORD_WINAPI DWORD WINAPI
301 * @brief Waits for a process to terminate and invokes the SIGCHLD handler
302 * @param proc pointer to process structure
305 ChildWaitThread (void *arg)
307 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg;
309 WaitForSingleObject (proc->handle, INFINITE);
311 if (w32_sigchld_handler)
312 w32_sigchld_handler ();
319 * Set process priority
321 * @param proc pointer to process structure
322 * @param prio priority value
323 * @return GNUNET_OK on success, GNUNET_SYSERR on error
326 GNUNET_OS_set_process_priority (struct GNUNET_OS_Process *proc,
327 enum GNUNET_SCHEDULER_Priority prio)
331 GNUNET_assert (prio < GNUNET_SCHEDULER_PRIORITY_COUNT);
332 if (prio == GNUNET_SCHEDULER_PRIORITY_KEEP)
335 /* convert to MINGW/Unix values */
338 case GNUNET_SCHEDULER_PRIORITY_UI:
339 case GNUNET_SCHEDULER_PRIORITY_URGENT:
341 rprio = HIGH_PRIORITY_CLASS;
347 case GNUNET_SCHEDULER_PRIORITY_HIGH:
349 rprio = ABOVE_NORMAL_PRIORITY_CLASS;
355 case GNUNET_SCHEDULER_PRIORITY_DEFAULT:
357 rprio = NORMAL_PRIORITY_CLASS;
363 case GNUNET_SCHEDULER_PRIORITY_BACKGROUND:
365 rprio = BELOW_NORMAL_PRIORITY_CLASS;
371 case GNUNET_SCHEDULER_PRIORITY_IDLE:
373 rprio = IDLE_PRIORITY_CLASS;
380 return GNUNET_SYSERR;
383 /* Set process priority */
386 HANDLE h = proc->handle;
388 GNUNET_assert (h != NULL);
389 SetPriorityClass (h, rprio);
395 if ((0 == pid) || (pid == getpid ()))
398 int delta = rprio - have;
401 if ((delta != 0) && (rprio == nice (delta)) && (errno != 0))
403 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
405 return GNUNET_SYSERR;
410 if (0 != setpriority (PRIO_PROCESS, pid, rprio))
412 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
414 return GNUNET_SYSERR;
419 LOG (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK,
420 "Priority management not availabe for this platform\n");
428 CreateCustomEnvTable (char **vars)
430 char *win32_env_table, *ptr, **var_ptr, *result, *result_ptr;
431 size_t tablesize = 0;
432 size_t items_count = 0;
433 size_t n_found = 0, n_var;
440 win32_env_table = GetEnvironmentStringsA ();
441 if (win32_env_table == NULL)
443 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++);
445 index = GNUNET_malloc (sizeof (char *) * n_var);
446 for (c = 0; c < n_var; c++)
448 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
450 size_t len = strlen (ptr);
453 for (var_ptr = vars; *var_ptr; var_ptr++)
457 var_len = strlen (var);
458 if (strncmp (var, ptr, var_len) == 0)
462 tablesize += var_len + strlen (val) + 1;
467 tablesize += len + 1;
470 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
475 n_found += strlen (var) + strlen (val) + 1;
477 result = GNUNET_malloc (tablesize + n_found + 1);
478 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
480 size_t len = strlen (ptr);
483 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
487 var_len = strlen (var);
488 if (strncmp (var, ptr, var_len) == 0)
496 strcpy (result_ptr, ptr);
497 result_ptr += len + 1;
501 strcpy (result_ptr, var);
502 result_ptr += var_len;
503 strcpy (result_ptr, val);
504 result_ptr += strlen (val) + 1;
508 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
512 var_len = strlen (var);
515 strcpy (result_ptr, var);
516 result_ptr += var_len;
517 strcpy (result_ptr, val);
518 result_ptr += strlen (val) + 1;
521 FreeEnvironmentStrings (win32_env_table);
532 * @param pipe_stdin pipe to use to send input to child process (or NULL)
533 * @param pipe_stdout pipe to use to get output from child process (or NULL)
534 * @param filename name of the binary
535 * @param va NULL-terminated list of arguments to the process
536 * @return pointer to process structure of the new process, NULL on error
538 struct GNUNET_OS_Process *
539 GNUNET_OS_start_process_va (struct GNUNET_DISK_PipeHandle *pipe_stdin,
540 struct GNUNET_DISK_PipeHandle *pipe_stdout,
541 const char *filename, va_list va)
545 #if ENABLE_WINDOWS_WORKAROUNDS
546 char *childpipename = NULL;
547 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
549 struct GNUNET_OS_Process *gnunet_proc = NULL;
560 #if ENABLE_WINDOWS_WORKAROUNDS
562 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
563 GNUNET_DISK_PERM_USER_READ |
564 GNUNET_DISK_PERM_USER_WRITE);
565 if (control_pipe == NULL)
571 while (NULL != va_arg (ap, char *))
575 argv = GNUNET_malloc (sizeof (char *) * (argc + 1));
578 while (NULL != (argv[argc] = va_arg (ap, char *)))
582 if (pipe_stdout != NULL)
584 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
586 GNUNET_DISK_PIPE_END_WRITE),
587 &fd_stdout_write, sizeof (int));
588 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
590 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
597 GNUNET_DISK_PIPE_END_READ),
598 &fd_stdin_read, sizeof (int));
599 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
601 GNUNET_DISK_PIPE_END_WRITE),
602 &fd_stdin_write, sizeof (int));
605 #if HAVE_WORKING_VFORK
614 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
615 #if ENABLE_WINDOWS_WORKAROUNDS
616 GNUNET_DISK_npipe_close (control_pipe);
622 #if HAVE_WORKING_VFORK
623 /* let's hope vfork actually works; for some extreme cases (including
624 * a testcase) we need 'execvp' to have run before we return, since
625 * we may send a signal to the process next and we don't want it
626 * to be caught by OUR signal handler (but either by the default
627 * handler or the actual handler as installed by the process itself). */
629 /* let's give the child process a chance to run execvp, 1s should
630 * be plenty in practice */
631 if (pipe_stdout != NULL)
632 GNUNET_DISK_pipe_close_end (pipe_stdout,
633 GNUNET_DISK_PIPE_END_WRITE);
634 if (pipe_stdin != NULL)
635 GNUNET_DISK_pipe_close_end (pipe_stdin,
636 GNUNET_DISK_PIPE_END_READ);
639 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
640 gnunet_proc->pid = ret;
641 #if ENABLE_WINDOWS_WORKAROUNDS
642 gnunet_proc->control_pipe = control_pipe;
646 #if ENABLE_WINDOWS_WORKAROUNDS
647 GNUNET_free (childpipename);
652 #if ENABLE_WINDOWS_WORKAROUNDS
653 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
654 GNUNET_free (childpipename);
657 if (pipe_stdout != NULL)
659 GNUNET_break (0 == close (fd_stdout_read));
660 if (-1 == dup2 (fd_stdout_write, 1))
661 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
662 GNUNET_break (0 == close (fd_stdout_write));
665 if (pipe_stdin != NULL)
668 GNUNET_break (0 == close (fd_stdin_write));
669 if (-1 == dup2 (fd_stdin_read, 0))
670 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
671 GNUNET_break (0 == close (fd_stdin_read));
673 execvp (filename, argv);
674 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
681 PROCESS_INFORMATION proc;
684 HANDLE stdout_handle;
686 char path[MAX_PATH + 1];
688 char *our_env[3] = { NULL, NULL, NULL };
689 char *env_block = NULL;
691 DWORD pathbuf_len, alloc_len;
696 char *non_const_filename;
698 /* Search in prefix dir (hopefully - the directory from which
699 * the current module was loaded), bindir and libdir, then in PATH
701 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
702 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
703 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
705 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
708 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
711 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
714 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
715 GNUNET_free (self_prefix);
716 GNUNET_free (bindir);
717 GNUNET_free (libdir);
719 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
720 GNUNET_assert (alloc_len == (pathbuf_len - 1));
722 cmdlen = strlen (filename);
723 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
724 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
726 GNUNET_asprintf (&non_const_filename, "%s", filename);
728 /* Check that this is the full path. If it isn't, search. */
729 if (non_const_filename[1] == ':')
730 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
731 else if (!SearchPathA
732 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
735 SetErrnoFromWinError (GetLastError ());
736 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
738 GNUNET_free (non_const_filename);
739 GNUNET_free (pathbuf);
742 GNUNET_free (pathbuf);
743 GNUNET_free (non_const_filename);
747 while (NULL != (arg = va_arg (ap, char *)))
750 cmdlen = cmdlen + strlen (path) + 3;
752 cmdlen = cmdlen + strlen (arg) + 3;
756 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
758 while (NULL != (arg = va_arg (ap, char *)))
761 idx += sprintf (idx, "\"%s\" ", path);
763 idx += sprintf (idx, "\"%s\" ", arg);
767 memset (&start, 0, sizeof (start));
768 start.cb = sizeof (start);
770 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
771 start.dwFlags |= STARTF_USESTDHANDLES;
773 if (pipe_stdin != NULL)
775 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
777 GNUNET_DISK_PIPE_END_READ),
778 &stdin_handle, sizeof (HANDLE));
779 start.hStdInput = stdin_handle;
782 if (pipe_stdout != NULL)
784 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
786 GNUNET_DISK_PIPE_END_WRITE),
787 &stdout_handle, sizeof (HANDLE));
788 start.hStdOutput = stdout_handle;
792 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
793 GNUNET_DISK_PERM_USER_READ |
794 GNUNET_DISK_PERM_USER_WRITE);
795 if (control_pipe == NULL)
803 LOG (GNUNET_ERROR_TYPE_DEBUG,
804 "Opened the parent end of the pipe `%s'\n", childpipename);
807 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
808 GNUNET_asprintf (&our_env[1], "%s", childpipename);
810 env_block = CreateCustomEnvTable (our_env);
811 GNUNET_free (our_env[0]);
812 GNUNET_free (our_env[1]);
815 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
816 env_block, NULL, &start, &proc))
818 SetErrnoFromWinError (GetLastError ());
819 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
820 GNUNET_free (env_block);
825 GNUNET_free (env_block);
827 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
828 gnunet_proc->pid = proc.dwProcessId;
829 gnunet_proc->handle = proc.hProcess;
830 gnunet_proc->control_pipe = control_pipe;
832 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
834 ResumeThread (proc.hThread);
835 CloseHandle (proc.hThread);
847 * @param pipe_stdin pipe to use to send input to child process (or NULL)
848 * @param pipe_stdout pipe to use to get output from child process (or NULL)
849 * @param filename name of the binary
850 * @param ... NULL-terminated list of arguments to the process
852 * @return pointer to process structure of the new process, NULL on error
855 struct GNUNET_OS_Process *
856 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
857 struct GNUNET_DISK_PipeHandle *pipe_stdout,
858 const char *filename, ...)
860 struct GNUNET_OS_Process *ret;
863 va_start (ap, filename);
864 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
873 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
874 * must be NULL on platforms where dup is not supported
875 * @param filename name of the binary
876 * @param argv NULL-terminated list of arguments to the process
877 * @return process ID of the new process, -1 on error
879 struct GNUNET_OS_Process *
880 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
883 #if ENABLE_WINDOWS_WORKAROUNDS
884 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
885 char *childpipename = NULL;
892 struct GNUNET_OS_Process *gnunet_proc = NULL;
901 #if ENABLE_WINDOWS_WORKAROUNDS
903 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
904 GNUNET_DISK_PERM_USER_READ |
905 GNUNET_DISK_PERM_USER_WRITE);
906 if (control_pipe == NULL)
915 while (-1 != (k = lsocks[i++]))
916 GNUNET_array_append (lscp, ls, k);
917 GNUNET_array_append (lscp, ls, -1);
919 #if HAVE_WORKING_VFORK
928 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
929 #if ENABLE_WINDOWS_WORKAROUNDS
930 GNUNET_DISK_npipe_close (control_pipe);
935 #if HAVE_WORKING_VFORK
936 /* let's hope vfork actually works; for some extreme cases (including
937 * a testcase) we need 'execvp' to have run before we return, since
938 * we may send a signal to the process next and we don't want it
939 * to be caught by OUR signal handler (but either by the default
940 * handler or the actual handler as installed by the process itself). */
942 /* let's give the child process a chance to run execvp, 1s should
943 * be plenty in practice */
946 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
947 gnunet_proc->pid = ret;
948 #if ENABLE_WINDOWS_WORKAROUNDS
949 gnunet_proc->control_pipe = control_pipe;
953 GNUNET_array_grow (lscp, ls, 0);
954 #if ENABLE_WINDOWS_WORKAROUNDS
955 GNUNET_free (childpipename);
960 #if ENABLE_WINDOWS_WORKAROUNDS
961 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
962 GNUNET_free (childpipename);
967 /* read systemd documentation... */
968 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
969 setenv ("LISTEN_PID", lpid, 1);
972 while (-1 != lscp[i])
975 while (-1 != lscp[j])
981 GNUNET_assert (-1 != k);
982 GNUNET_assert (0 == close (lscp[j]));
990 /* Bury any existing FD, no matter what; they should all be closed
991 * on exec anyway and the important onces have been dup'ed away */
993 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
995 /* unset close-on-exec flag */
996 flags = fcntl (tgt, F_GETFD);
997 GNUNET_assert (flags >= 0);
998 flags &= ~FD_CLOEXEC;
1000 (void) fcntl (tgt, F_SETFD, flags);
1004 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
1005 setenv ("LISTEN_FDS", fds, 1);
1007 GNUNET_array_grow (lscp, ls, 0);
1008 execvp (filename, argv);
1009 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
1012 char **arg, **non_const_argv;
1013 unsigned int cmdlen;
1016 PROCESS_INFORMATION proc;
1018 struct GNUNET_OS_Process *gnunet_proc = NULL;
1020 char path[MAX_PATH + 1];
1022 char *our_env[3] = { NULL, NULL, NULL };
1023 char *env_block = NULL;
1025 DWORD pathbuf_len, alloc_len;
1030 char *non_const_filename;
1032 GNUNET_assert (lsocks == NULL);
1034 /* Search in prefix dir (hopefully - the directory from which
1035 * the current module was loaded), bindir and libdir, then in PATH
1037 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1038 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1039 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1041 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1044 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1047 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1050 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1051 GNUNET_free (self_prefix);
1052 GNUNET_free (bindir);
1053 GNUNET_free (libdir);
1055 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1056 if (alloc_len != pathbuf_len - 1)
1058 GNUNET_free (pathbuf);
1059 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1063 cmdlen = strlen (filename);
1064 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1065 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1067 GNUNET_asprintf (&non_const_filename, "%s", filename);
1069 /* Check that this is the full path. If it isn't, search. */
1070 if (non_const_filename[1] == ':')
1071 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1072 else if (!SearchPathA
1073 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1076 SetErrnoFromWinError (GetLastError ());
1077 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1078 non_const_filename);
1079 GNUNET_free (non_const_filename);
1080 GNUNET_free (pathbuf);
1083 GNUNET_free (pathbuf);
1084 GNUNET_free (non_const_filename);
1086 /* Count the number of arguments */
1087 arg = (char **) argv;
1094 /* Allocate a copy argv */
1095 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1097 /* Copy all argv strings */
1099 arg = (char **) argv;
1103 non_const_argv[argcount] = GNUNET_strdup (path);
1105 non_const_argv[argcount] = GNUNET_strdup (*arg);
1109 non_const_argv[argcount] = NULL;
1113 arg = non_const_argv;
1116 cmdlen = cmdlen + strlen (*arg) + 3;
1120 /* Allocate and create cmd */
1121 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1122 arg = non_const_argv;
1125 idx += sprintf (idx, "\"%s\" ", *arg);
1129 while (argcount > 0)
1130 GNUNET_free (non_const_argv[--argcount]);
1131 GNUNET_free (non_const_argv);
1133 memset (&start, 0, sizeof (start));
1134 start.cb = sizeof (start);
1137 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1138 GNUNET_DISK_PERM_USER_READ |
1139 GNUNET_DISK_PERM_USER_WRITE);
1140 if (control_pipe == NULL)
1148 LOG (GNUNET_ERROR_TYPE_DEBUG,
1149 "Opened the parent end of the pipe `%s'\n", childpipename);
1152 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1153 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1155 env_block = CreateCustomEnvTable (our_env);
1156 GNUNET_free (our_env[0]);
1157 GNUNET_free (our_env[1]);
1160 (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1161 env_block, NULL, &start, &proc))
1163 SetErrnoFromWinError (GetLastError ());
1164 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1165 GNUNET_free (env_block);
1170 GNUNET_free (env_block);
1172 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1173 gnunet_proc->pid = proc.dwProcessId;
1174 gnunet_proc->handle = proc.hProcess;
1175 gnunet_proc->control_pipe = control_pipe;
1177 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1179 ResumeThread (proc.hThread);
1180 CloseHandle (proc.hThread);
1189 * Retrieve the status of a process
1190 * @param proc process ID
1191 * @param type status type
1192 * @param code return code/signal number
1193 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1196 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1197 enum GNUNET_OS_ProcessStatusType *type,
1198 unsigned long *code)
1204 GNUNET_assert (0 != proc);
1205 ret = waitpid (proc->pid, &status, WNOHANG);
1208 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1209 return GNUNET_SYSERR;
1213 *type = GNUNET_OS_PROCESS_RUNNING;
1217 if (proc->pid != ret)
1219 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1220 return GNUNET_SYSERR;
1222 if (WIFEXITED (status))
1224 *type = GNUNET_OS_PROCESS_EXITED;
1225 *code = WEXITSTATUS (status);
1227 else if (WIFSIGNALED (status))
1229 *type = GNUNET_OS_PROCESS_SIGNALED;
1230 *code = WTERMSIG (status);
1232 else if (WIFSTOPPED (status))
1234 *type = GNUNET_OS_PROCESS_SIGNALED;
1235 *code = WSTOPSIG (status);
1238 else if (WIFCONTINUED (status))
1240 *type = GNUNET_OS_PROCESS_RUNNING;
1246 *type = GNUNET_OS_PROCESS_UNKNOWN;
1251 DWORD c, error_code, ret;
1255 if (h == NULL || ret == 0)
1257 LOG (GNUNET_ERROR_TYPE_WARNING,
1258 "Invalid process information {%d, %08X}\n", ret, h);
1259 return GNUNET_SYSERR;
1262 h = GetCurrentProcess ();
1265 ret = GetExitCodeProcess (h, &c);
1266 error_code = GetLastError ();
1267 if (ret == 0 || error_code != NO_ERROR)
1269 SetErrnoFromWinError (error_code);
1270 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1271 return GNUNET_SYSERR;
1273 if (STILL_ACTIVE == c)
1275 *type = GNUNET_OS_PROCESS_RUNNING;
1279 *type = GNUNET_OS_PROCESS_EXITED;
1288 * Wait for a process
1289 * @param proc pointer to process structure
1290 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1293 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1297 pid_t pid = proc->pid;
1299 if (pid != waitpid (pid, NULL, 0))
1300 return GNUNET_SYSERR;
1309 LOG (GNUNET_ERROR_TYPE_WARNING,
1310 "Invalid process information {%d, %08X}\n", proc->pid, h);
1311 return GNUNET_SYSERR;
1314 h = GetCurrentProcess ();
1316 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1318 SetErrnoFromWinError (GetLastError ());
1319 ret = GNUNET_SYSERR;
1330 * Handle to a command.
1332 struct GNUNET_OS_CommandHandle
1338 struct GNUNET_OS_Process *eip;
1341 * Handle to the output pipe.
1343 struct GNUNET_DISK_PipeHandle *opipe;
1346 * Read-end of output pipe.
1348 const struct GNUNET_DISK_FileHandle *r;
1351 * Function to call on each line of output.
1353 GNUNET_OS_LineProcessor proc;
1356 * Closure for 'proc'.
1361 * Buffer for the output.
1366 * Task reading from pipe.
1368 GNUNET_SCHEDULER_TaskIdentifier rtask;
1373 struct GNUNET_TIME_Absolute timeout;
1376 * Current read offset in buf.
1383 * Stop/kill a command. Must ONLY be called either from
1384 * the callback after 'NULL' was passed for 'line' *OR*
1385 * from an independent task (not within the line processor).
1387 * @param cmd handle to the process
1390 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1393 if (cmd->proc != NULL)
1395 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1396 GNUNET_SCHEDULER_cancel (cmd->rtask);
1398 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1399 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1400 GNUNET_OS_process_close (cmd->eip);
1401 GNUNET_DISK_pipe_close (cmd->opipe);
1407 * Read from the process and call the line processor.
1409 * @param cls the 'struct GNUNET_OS_CommandHandle'
1410 * @param tc scheduler context
1413 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1415 struct GNUNET_OS_CommandHandle *cmd = cls;
1416 GNUNET_OS_LineProcessor proc;
1420 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1422 GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1424 /* timeout, shutdown, etc. */
1427 proc (cmd->proc_cls, NULL);
1431 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1432 sizeof (cmd->buf) - cmd->off);
1435 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1437 cmd->buf[cmd->off] = '\0';
1438 cmd->proc (cmd->proc_cls, cmd->buf);
1442 proc (cmd->proc_cls, NULL);
1445 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1450 cmd->proc (cmd->proc_cls, cmd->buf);
1451 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1452 cmd->off -= (end + 1 - cmd->buf);
1453 end = memchr (cmd->buf, '\n', cmd->off);
1456 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1457 (cmd->timeout), cmd->r, &cmd_read, cmd);
1462 * Run the given command line and call the given function
1463 * for each line of the output.
1465 * @param proc function to call for each line of the output
1466 * @param proc_cls closure for proc
1467 * @param timeout when to time out
1468 * @param binary command to run
1469 * @param ... arguments to command
1470 * @return NULL on error
1472 struct GNUNET_OS_CommandHandle *
1473 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1474 struct GNUNET_TIME_Relative timeout,
1475 const char *binary, ...)
1477 struct GNUNET_OS_CommandHandle *cmd;
1478 struct GNUNET_OS_Process *eip;
1479 struct GNUNET_DISK_PipeHandle *opipe;
1482 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1485 va_start (ap, binary);
1486 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1490 GNUNET_DISK_pipe_close (opipe);
1493 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1494 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1495 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1499 cmd->proc_cls = proc_cls;
1500 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1502 GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1509 /* end of os_priority.c */