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));
598 #if HAVE_WORKING_VFORK
607 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
608 #if ENABLE_WINDOWS_WORKAROUNDS
609 GNUNET_DISK_npipe_close (control_pipe);
615 #if HAVE_WORKING_VFORK
616 /* let's hope vfork actually works; for some extreme cases (including
617 * a testcase) we need 'execvp' to have run before we return, since
618 * we may send a signal to the process next and we don't want it
619 * to be caught by OUR signal handler (but either by the default
620 * handler or the actual handler as installed by the process itself). */
622 /* let's give the child process a chance to run execvp, 1s should
623 * be plenty in practice */
624 if (pipe_stdout != NULL)
625 GNUNET_DISK_pipe_close_end (pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
626 if (pipe_stdin != NULL)
627 GNUNET_DISK_pipe_close_end (pipe_stdin, GNUNET_DISK_PIPE_END_READ);
630 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
631 gnunet_proc->pid = ret;
632 #if ENABLE_WINDOWS_WORKAROUNDS
633 gnunet_proc->control_pipe = control_pipe;
637 #if ENABLE_WINDOWS_WORKAROUNDS
638 GNUNET_free (childpipename);
643 #if ENABLE_WINDOWS_WORKAROUNDS
644 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
645 GNUNET_free (childpipename);
648 if (pipe_stdout != NULL)
650 GNUNET_break (0 == close (fd_stdout_read));
651 if (-1 == dup2 (fd_stdout_write, 1))
652 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
653 GNUNET_break (0 == close (fd_stdout_write));
656 if (pipe_stdin != NULL)
659 GNUNET_break (0 == close (fd_stdin_write));
660 if (-1 == dup2 (fd_stdin_read, 0))
661 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2");
662 GNUNET_break (0 == close (fd_stdin_read));
664 execvp (filename, argv);
665 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
672 PROCESS_INFORMATION proc;
675 HANDLE stdout_handle;
677 char path[MAX_PATH + 1];
679 char *our_env[3] = { NULL, NULL, NULL };
680 char *env_block = NULL;
682 DWORD pathbuf_len, alloc_len;
687 char *non_const_filename;
689 /* Search in prefix dir (hopefully - the directory from which
690 * the current module was loaded), bindir and libdir, then in PATH
692 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
693 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
694 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
696 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
699 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
702 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
705 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
706 GNUNET_free (self_prefix);
707 GNUNET_free (bindir);
708 GNUNET_free (libdir);
710 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
711 GNUNET_assert (alloc_len == (pathbuf_len - 1));
713 cmdlen = strlen (filename);
714 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
715 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
717 GNUNET_asprintf (&non_const_filename, "%s", filename);
719 /* Check that this is the full path. If it isn't, search. */
720 if (non_const_filename[1] == ':')
721 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
722 else if (!SearchPathA
723 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
726 SetErrnoFromWinError (GetLastError ());
727 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
729 GNUNET_free (non_const_filename);
730 GNUNET_free (pathbuf);
733 GNUNET_free (pathbuf);
734 GNUNET_free (non_const_filename);
738 while (NULL != (arg = va_arg (ap, char *)))
741 cmdlen = cmdlen + strlen (path) + 3;
743 cmdlen = cmdlen + strlen (arg) + 3;
747 cmd = idx = GNUNET_malloc (sizeof (char) * (cmdlen + 1));
749 while (NULL != (arg = va_arg (ap, char *)))
752 idx += sprintf (idx, "\"%s\" ", path);
754 idx += sprintf (idx, "\"%s\" ", arg);
758 memset (&start, 0, sizeof (start));
759 start.cb = sizeof (start);
761 if ((pipe_stdin != NULL) || (pipe_stdout != NULL))
762 start.dwFlags |= STARTF_USESTDHANDLES;
764 if (pipe_stdin != NULL)
766 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
767 (pipe_stdin, GNUNET_DISK_PIPE_END_READ),
768 &stdin_handle, sizeof (HANDLE));
769 start.hStdInput = stdin_handle;
772 if (pipe_stdout != NULL)
774 GNUNET_DISK_internal_file_handle_ (GNUNET_DISK_pipe_handle
776 GNUNET_DISK_PIPE_END_WRITE),
777 &stdout_handle, sizeof (HANDLE));
778 start.hStdOutput = stdout_handle;
782 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
783 GNUNET_DISK_PERM_USER_READ |
784 GNUNET_DISK_PERM_USER_WRITE);
785 if (control_pipe == NULL)
793 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
797 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
798 GNUNET_asprintf (&our_env[1], "%s", childpipename);
800 env_block = CreateCustomEnvTable (our_env);
801 GNUNET_free (our_env[0]);
802 GNUNET_free (our_env[1]);
805 (path, cmd, NULL, NULL, TRUE, DETACHED_PROCESS | CREATE_SUSPENDED,
806 env_block, NULL, &start, &proc))
808 SetErrnoFromWinError (GetLastError ());
809 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "CreateProcess", path);
810 GNUNET_free (env_block);
815 GNUNET_free (env_block);
817 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
818 gnunet_proc->pid = proc.dwProcessId;
819 gnunet_proc->handle = proc.hProcess;
820 gnunet_proc->control_pipe = control_pipe;
822 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
824 ResumeThread (proc.hThread);
825 CloseHandle (proc.hThread);
837 * @param pipe_stdin pipe to use to send input to child process (or NULL)
838 * @param pipe_stdout pipe to use to get output from child process (or NULL)
839 * @param filename name of the binary
840 * @param ... NULL-terminated list of arguments to the process
842 * @return pointer to process structure of the new process, NULL on error
845 struct GNUNET_OS_Process *
846 GNUNET_OS_start_process (struct GNUNET_DISK_PipeHandle *pipe_stdin,
847 struct GNUNET_DISK_PipeHandle *pipe_stdout,
848 const char *filename, ...)
850 struct GNUNET_OS_Process *ret;
853 va_start (ap, filename);
854 ret = GNUNET_OS_start_process_va (pipe_stdin, pipe_stdout, filename, ap);
863 * @param lsocks array of listen sockets to dup systemd-style (or NULL);
864 * must be NULL on platforms where dup is not supported
865 * @param filename name of the binary
866 * @param argv NULL-terminated list of arguments to the process
867 * @return process ID of the new process, -1 on error
869 struct GNUNET_OS_Process *
870 GNUNET_OS_start_process_v (const int *lsocks, const char *filename,
873 #if ENABLE_WINDOWS_WORKAROUNDS
874 struct GNUNET_DISK_FileHandle *control_pipe = NULL;
875 char *childpipename = NULL;
882 struct GNUNET_OS_Process *gnunet_proc = NULL;
891 #if ENABLE_WINDOWS_WORKAROUNDS
893 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
894 GNUNET_DISK_PERM_USER_READ |
895 GNUNET_DISK_PERM_USER_WRITE);
896 if (control_pipe == NULL)
905 while (-1 != (k = lsocks[i++]))
906 GNUNET_array_append (lscp, ls, k);
907 GNUNET_array_append (lscp, ls, -1);
909 #if HAVE_WORKING_VFORK
918 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork");
919 #if ENABLE_WINDOWS_WORKAROUNDS
920 GNUNET_DISK_npipe_close (control_pipe);
925 #if HAVE_WORKING_VFORK
926 /* let's hope vfork actually works; for some extreme cases (including
927 * a testcase) we need 'execvp' to have run before we return, since
928 * we may send a signal to the process next and we don't want it
929 * to be caught by OUR signal handler (but either by the default
930 * handler or the actual handler as installed by the process itself). */
932 /* let's give the child process a chance to run execvp, 1s should
933 * be plenty in practice */
936 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
937 gnunet_proc->pid = ret;
938 #if ENABLE_WINDOWS_WORKAROUNDS
939 gnunet_proc->control_pipe = control_pipe;
943 GNUNET_array_grow (lscp, ls, 0);
944 #if ENABLE_WINDOWS_WORKAROUNDS
945 GNUNET_free (childpipename);
950 #if ENABLE_WINDOWS_WORKAROUNDS
951 setenv (GNUNET_OS_CONTROL_PIPE, childpipename, 1);
952 GNUNET_free (childpipename);
957 /* read systemd documentation... */
958 GNUNET_snprintf (lpid, sizeof (lpid), "%u", getpid ());
959 setenv ("LISTEN_PID", lpid, 1);
962 while (-1 != lscp[i])
965 while (-1 != lscp[j])
971 GNUNET_assert (-1 != k);
972 GNUNET_assert (0 == close (lscp[j]));
980 /* Bury any existing FD, no matter what; they should all be closed
981 * on exec anyway and the important onces have been dup'ed away */
983 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
985 /* unset close-on-exec flag */
986 flags = fcntl (tgt, F_GETFD);
987 GNUNET_assert (flags >= 0);
988 flags &= ~FD_CLOEXEC;
990 (void) fcntl (tgt, F_SETFD, flags);
994 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
995 setenv ("LISTEN_FDS", fds, 1);
997 GNUNET_array_grow (lscp, ls, 0);
998 execvp (filename, argv);
999 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
1002 char **arg, **non_const_argv;
1003 unsigned int cmdlen;
1006 PROCESS_INFORMATION proc;
1008 struct GNUNET_OS_Process *gnunet_proc = NULL;
1010 char path[MAX_PATH + 1];
1012 char *our_env[3] = { NULL, NULL, NULL };
1013 char *env_block = NULL;
1015 DWORD pathbuf_len, alloc_len;
1020 char *non_const_filename;
1022 GNUNET_assert (lsocks == NULL);
1024 /* Search in prefix dir (hopefully - the directory from which
1025 * the current module was loaded), bindir and libdir, then in PATH
1027 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX);
1028 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR);
1029 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
1031 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0);
1034 pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 +
1037 pathbuf = GNUNET_malloc (alloc_len * sizeof (char));
1040 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
1041 GNUNET_free (self_prefix);
1042 GNUNET_free (bindir);
1043 GNUNET_free (libdir);
1045 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len);
1046 if (alloc_len != pathbuf_len - 1)
1048 GNUNET_free (pathbuf);
1049 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
1053 cmdlen = strlen (filename);
1054 if (cmdlen < 5 || strcmp (&filename[cmdlen - 4], ".exe") != 0)
1055 GNUNET_asprintf (&non_const_filename, "%s.exe", filename);
1057 GNUNET_asprintf (&non_const_filename, "%s", filename);
1059 /* Check that this is the full path. If it isn't, search. */
1060 if (non_const_filename[1] == ':')
1061 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename);
1062 else if (!SearchPathA
1063 (pathbuf, non_const_filename, NULL, sizeof (path) / sizeof (char),
1066 SetErrnoFromWinError (GetLastError ());
1067 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "SearchPath",
1068 non_const_filename);
1069 GNUNET_free (non_const_filename);
1070 GNUNET_free (pathbuf);
1073 GNUNET_free (pathbuf);
1074 GNUNET_free (non_const_filename);
1076 /* Count the number of arguments */
1077 arg = (char **) argv;
1084 /* Allocate a copy argv */
1085 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1));
1087 /* Copy all argv strings */
1089 arg = (char **) argv;
1093 non_const_argv[argcount] = GNUNET_strdup (path);
1095 non_const_argv[argcount] = GNUNET_strdup (*arg);
1099 non_const_argv[argcount] = NULL;
1103 arg = non_const_argv;
1106 cmdlen = cmdlen + strlen (*arg) + 3;
1110 /* Allocate and create cmd */
1111 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen);
1112 arg = non_const_argv;
1115 idx += sprintf (idx, "\"%s\" ", *arg);
1119 while (argcount > 0)
1120 GNUNET_free (non_const_argv[--argcount]);
1121 GNUNET_free (non_const_argv);
1123 memset (&start, 0, sizeof (start));
1124 start.cb = sizeof (start);
1127 GNUNET_DISK_npipe_create (&childpipename, GNUNET_DISK_OPEN_WRITE,
1128 GNUNET_DISK_PERM_USER_READ |
1129 GNUNET_DISK_PERM_USER_WRITE);
1130 if (control_pipe == NULL)
1138 LOG (GNUNET_ERROR_TYPE_DEBUG, "Opened the parent end of the pipe `%s'\n",
1142 GNUNET_asprintf (&our_env[0], "%s=", GNUNET_OS_CONTROL_PIPE);
1143 GNUNET_asprintf (&our_env[1], "%s", childpipename);
1145 env_block = CreateCustomEnvTable (our_env);
1146 GNUNET_free (our_env[0]);
1147 GNUNET_free (our_env[1]);
1150 (path, cmd, NULL, NULL, FALSE, DETACHED_PROCESS | CREATE_SUSPENDED,
1151 env_block, NULL, &start, &proc))
1153 SetErrnoFromWinError (GetLastError ());
1154 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "CreateProcess");
1155 GNUNET_free (env_block);
1160 GNUNET_free (env_block);
1162 gnunet_proc = GNUNET_malloc (sizeof (struct GNUNET_OS_Process));
1163 gnunet_proc->pid = proc.dwProcessId;
1164 gnunet_proc->handle = proc.hProcess;
1165 gnunet_proc->control_pipe = control_pipe;
1167 CreateThread (NULL, 64000, ChildWaitThread, (void *) gnunet_proc, 0, NULL);
1169 ResumeThread (proc.hThread);
1170 CloseHandle (proc.hThread);
1179 * Retrieve the status of a process
1180 * @param proc process ID
1181 * @param type status type
1182 * @param code return code/signal number
1183 * @return GNUNET_OK on success, GNUNET_NO if the process is still running, GNUNET_SYSERR otherwise
1186 GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1187 enum GNUNET_OS_ProcessStatusType *type,
1188 unsigned long *code)
1194 GNUNET_assert (0 != proc);
1195 ret = waitpid (proc->pid, &status, WNOHANG);
1198 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1199 return GNUNET_SYSERR;
1203 *type = GNUNET_OS_PROCESS_RUNNING;
1207 if (proc->pid != ret)
1209 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid");
1210 return GNUNET_SYSERR;
1212 if (WIFEXITED (status))
1214 *type = GNUNET_OS_PROCESS_EXITED;
1215 *code = WEXITSTATUS (status);
1217 else if (WIFSIGNALED (status))
1219 *type = GNUNET_OS_PROCESS_SIGNALED;
1220 *code = WTERMSIG (status);
1222 else if (WIFSTOPPED (status))
1224 *type = GNUNET_OS_PROCESS_SIGNALED;
1225 *code = WSTOPSIG (status);
1228 else if (WIFCONTINUED (status))
1230 *type = GNUNET_OS_PROCESS_RUNNING;
1236 *type = GNUNET_OS_PROCESS_UNKNOWN;
1241 DWORD c, error_code, ret;
1245 if (h == NULL || ret == 0)
1247 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1249 return GNUNET_SYSERR;
1252 h = GetCurrentProcess ();
1255 ret = GetExitCodeProcess (h, &c);
1256 error_code = GetLastError ();
1257 if (ret == 0 || error_code != NO_ERROR)
1259 SetErrnoFromWinError (error_code);
1260 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1261 return GNUNET_SYSERR;
1263 if (STILL_ACTIVE == c)
1265 *type = GNUNET_OS_PROCESS_RUNNING;
1269 *type = GNUNET_OS_PROCESS_EXITED;
1278 * Wait for a process
1279 * @param proc pointer to process structure
1280 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
1283 GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1287 pid_t pid = proc->pid;
1289 if (pid != waitpid (pid, NULL, 0))
1290 return GNUNET_SYSERR;
1299 LOG (GNUNET_ERROR_TYPE_WARNING, "Invalid process information {%d, %08X}\n",
1301 return GNUNET_SYSERR;
1304 h = GetCurrentProcess ();
1306 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1308 SetErrnoFromWinError (GetLastError ());
1309 ret = GNUNET_SYSERR;
1320 * Handle to a command.
1322 struct GNUNET_OS_CommandHandle
1328 struct GNUNET_OS_Process *eip;
1331 * Handle to the output pipe.
1333 struct GNUNET_DISK_PipeHandle *opipe;
1336 * Read-end of output pipe.
1338 const struct GNUNET_DISK_FileHandle *r;
1341 * Function to call on each line of output.
1343 GNUNET_OS_LineProcessor proc;
1346 * Closure for 'proc'.
1351 * Buffer for the output.
1356 * Task reading from pipe.
1358 GNUNET_SCHEDULER_TaskIdentifier rtask;
1363 struct GNUNET_TIME_Absolute timeout;
1366 * Current read offset in buf.
1373 * Stop/kill a command. Must ONLY be called either from
1374 * the callback after 'NULL' was passed for 'line' *OR*
1375 * from an independent task (not within the line processor).
1377 * @param cmd handle to the process
1380 GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1383 if (cmd->proc != NULL)
1385 GNUNET_assert (GNUNET_SCHEDULER_NO_TASK != cmd->rtask);
1386 GNUNET_SCHEDULER_cancel (cmd->rtask);
1388 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL);
1389 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip));
1390 GNUNET_OS_process_close (cmd->eip);
1391 GNUNET_DISK_pipe_close (cmd->opipe);
1397 * Read from the process and call the line processor.
1399 * @param cls the 'struct GNUNET_OS_CommandHandle'
1400 * @param tc scheduler context
1403 cmd_read (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1405 struct GNUNET_OS_CommandHandle *cmd = cls;
1406 GNUNET_OS_LineProcessor proc;
1410 cmd->rtask = GNUNET_SCHEDULER_NO_TASK;
1411 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r))
1413 /* timeout, shutdown, etc. */
1416 proc (cmd->proc_cls, NULL);
1420 GNUNET_DISK_file_read (cmd->r, &cmd->buf[cmd->off],
1421 sizeof (cmd->buf) - cmd->off);
1424 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1426 cmd->buf[cmd->off] = '\0';
1427 cmd->proc (cmd->proc_cls, cmd->buf);
1431 proc (cmd->proc_cls, NULL);
1434 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1439 cmd->proc (cmd->proc_cls, cmd->buf);
1440 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1441 cmd->off -= (end + 1 - cmd->buf);
1442 end = memchr (cmd->buf, '\n', cmd->off);
1445 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining
1446 (cmd->timeout), cmd->r, &cmd_read, cmd);
1451 * Run the given command line and call the given function
1452 * for each line of the output.
1454 * @param proc function to call for each line of the output
1455 * @param proc_cls closure for proc
1456 * @param timeout when to time out
1457 * @param binary command to run
1458 * @param ... arguments to command
1459 * @return NULL on error
1461 struct GNUNET_OS_CommandHandle *
1462 GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, void *proc_cls,
1463 struct GNUNET_TIME_Relative timeout, const char *binary,
1466 struct GNUNET_OS_CommandHandle *cmd;
1467 struct GNUNET_OS_Process *eip;
1468 struct GNUNET_DISK_PipeHandle *opipe;
1471 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_NO, GNUNET_YES);
1474 va_start (ap, binary);
1475 eip = GNUNET_OS_start_process_va (NULL, opipe, binary, ap);
1479 GNUNET_DISK_pipe_close (opipe);
1482 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE);
1483 cmd = GNUNET_malloc (sizeof (struct GNUNET_OS_CommandHandle));
1484 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout);
1488 cmd->proc_cls = proc_cls;
1489 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ);
1490 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd);
1497 /* end of os_priority.c */