2 * Copyright (C) 2010-2011 Robert Ancell.
3 * Author: Robert Ancell <robert.ancell@canonical.com>
5 * This program is free software: you can redistribute it and/or modify it under
6 * the terms of the GNU General Public License as published by the Free Software
7 * Foundation, either version 3 of the License, or (at your option) any later
8 * version. See http://www.gnu.org/copyleft/gpl.html the full text of the
31 static guint signals[LAST_SIGNAL] = { 0 };
35 /* Function to run inside subprocess before exec */
36 ProcessRunFunc run_func;
37 gpointer run_func_data;
47 /* TRUE to clear the environment in this process */
48 gboolean clear_environment;
50 /* Environment variables to set */
56 /* Exit status of process */
59 /* TRUE if stopping this process (waiting for child process to stop) */
62 /* Timeout waiting for process to quit */
65 /* Watch on process */
69 G_DEFINE_TYPE (Process, process, G_TYPE_OBJECT);
71 static Process *current_process = NULL;
72 static GHashTable *processes = NULL;
73 static pid_t signal_pid;
74 static int signal_pipe[2];
77 process_get_current (void)
80 return current_process;
82 current_process = process_new (NULL, NULL);
83 current_process->priv->pid = getpid ();
85 return current_process;
89 process_new (ProcessRunFunc run_func, gpointer run_func_data)
91 Process *process = g_object_new (PROCESS_TYPE, NULL);
92 process->priv->run_func = run_func;
93 process->priv->run_func_data = run_func_data;
94 process->priv->log_mode = LOG_MODE_INVALID;
99 process_set_log_file (Process *process, const gchar *path, gboolean log_stdout, LogMode log_mode)
101 g_return_if_fail (process != NULL);
102 g_free (process->priv->log_file);
103 process->priv->log_file = g_strdup (path);
104 process->priv->log_stdout = log_stdout;
105 process->priv->log_mode = log_mode;
109 process_set_clear_environment (Process *process, gboolean clear_environment)
111 g_return_if_fail (process != NULL);
112 process->priv->clear_environment = clear_environment;
116 process_get_clear_environment (Process *process)
118 g_return_val_if_fail (process != NULL, FALSE);
119 return process->priv->clear_environment;
123 process_set_env (Process *process, const gchar *name, const gchar *value)
125 g_return_if_fail (process != NULL);
126 g_return_if_fail (name != NULL);
127 g_hash_table_insert (process->priv->env, g_strdup (name), g_strdup (value));
131 process_get_env (Process *process, const gchar *name)
133 g_return_val_if_fail (process != NULL, NULL);
134 g_return_val_if_fail (name != NULL, NULL);
135 return g_hash_table_lookup (process->priv->env, name);
139 process_set_command (Process *process, const gchar *command)
141 g_return_if_fail (process != NULL);
143 g_free (process->priv->command);
144 process->priv->command = g_strdup (command);
148 process_get_command (Process *process)
150 g_return_val_if_fail (process != NULL, NULL);
151 return process->priv->command;
155 process_watch_cb (GPid pid, gint status, gpointer data)
157 Process *process = data;
159 process->priv->watch = 0;
160 process->priv->exit_status = status;
162 if (WIFEXITED (status))
163 g_debug ("Process %d exited with return value %d", pid, WEXITSTATUS (status));
164 else if (WIFSIGNALED (status))
165 g_debug ("Process %d terminated with signal %d", pid, WTERMSIG (status));
167 if (process->priv->quit_timeout)
168 g_source_remove (process->priv->quit_timeout);
169 process->priv->quit_timeout = 0;
170 process->priv->pid = 0;
171 g_hash_table_remove (processes, GINT_TO_POINTER (pid));
173 g_signal_emit (process, signals[STOPPED], 0);
177 process_start (Process *process, gboolean block)
181 gchar **env_keys, **env_values;
186 GError *error = NULL;
188 g_return_val_if_fail (process != NULL, FALSE);
189 g_return_val_if_fail (process->priv->command != NULL, FALSE);
190 g_return_val_if_fail (process->priv->pid == 0, FALSE);
192 if (!g_shell_parse_argv (process->priv->command, &argc, &argv, &error))
194 g_warning ("Error parsing command %s: %s", process->priv->command, error->message);
198 if (process->priv->log_file)
199 log_fd = log_file_open (process->priv->log_file, process->priv->log_mode);
201 /* Work out variables to set */
202 env_length = g_hash_table_size (process->priv->env);
203 env_keys = g_malloc (sizeof (gchar *) * env_length);
204 env_values = g_malloc (sizeof (gchar *) * env_length);
205 keys = g_hash_table_get_keys (process->priv->env);
206 for (i = 0, link = keys; i < env_length; i++, link = link->next)
208 env_keys[i] = link->data;
209 env_values[i] = g_hash_table_lookup (process->priv->env, env_keys[i]);
216 /* Do custom setup */
217 if (process->priv->run_func)
218 process->priv->run_func (process, process->priv->run_func_data);
220 /* Redirect output to logfile */
223 if (process->priv->log_stdout)
224 dup2 (log_fd, STDOUT_FILENO);
225 dup2 (log_fd, STDERR_FILENO);
229 /* Set environment */
230 if (process->priv->clear_environment)
236 for (i = 0; i < env_length; i++)
237 setenv (env_keys[i], env_values[i], TRUE);
239 execvp (argv[0], argv);
240 _exit (EXIT_FAILURE);
250 g_warning ("Failed to fork: %s", strerror (errno));
254 g_debug ("Launching process %d: %s", pid, process->priv->command);
256 process->priv->pid = pid;
261 waitpid (process->priv->pid, &exit_status, 0);
262 process_watch_cb (process->priv->pid, exit_status, process);
266 g_hash_table_insert (processes, GINT_TO_POINTER (process->priv->pid), g_object_ref (process));
267 process->priv->watch = g_child_watch_add (process->priv->pid, process_watch_cb, process);
274 process_get_is_running (Process *process)
276 g_return_val_if_fail (process != NULL, FALSE);
277 return process->priv->pid != 0;
281 process_get_pid (Process *process)
283 g_return_val_if_fail (process != NULL, 0);
284 return process->priv->pid;
288 process_signal (Process *process, int signum)
290 g_return_if_fail (process != NULL);
292 if (process->priv->pid == 0)
295 g_debug ("Sending signal %d to process %d", signum, process->priv->pid);
297 if (kill (process->priv->pid, signum) < 0)
299 /* Ignore ESRCH, we will pick that up in our wait */
301 g_warning ("Error sending signal %d to process %d: %s", signum, process->priv->pid, strerror (errno));
306 quit_timeout_cb (Process *process)
308 process->priv->quit_timeout = 0;
309 process_signal (process, SIGKILL);
314 process_stop (Process *process)
316 g_return_if_fail (process != NULL);
318 if (process->priv->stopping)
320 process->priv->stopping = TRUE;
322 /* If already stopped then we're done! */
323 if (process->priv->pid == 0)
326 /* Send SIGTERM, and then SIGKILL if no response */
327 process->priv->quit_timeout = g_timeout_add (5000, (GSourceFunc) quit_timeout_cb, process);
328 process_signal (process, SIGTERM);
332 process_get_exit_status (Process *process)
334 g_return_val_if_fail (process != NULL, -1);
335 return process->priv->exit_status;
339 process_init (Process *process)
341 process->priv = G_TYPE_INSTANCE_GET_PRIVATE (process, PROCESS_TYPE, ProcessPrivate);
342 process->priv->env = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);
346 process_stopped (Process *process)
351 process_finalize (GObject *object)
353 Process *self = PROCESS (object);
355 if (self->priv->pid > 0)
356 g_hash_table_remove (processes, GINT_TO_POINTER (self->priv->pid));
358 g_free (self->priv->log_file);
359 g_free (self->priv->command);
360 g_hash_table_unref (self->priv->env);
361 if (self->priv->quit_timeout)
362 g_source_remove (self->priv->quit_timeout);
363 if (self->priv->watch)
364 g_source_remove (self->priv->watch);
367 kill (self->priv->pid, SIGTERM);
369 G_OBJECT_CLASS (process_parent_class)->finalize (object);
373 signal_cb (int signum, siginfo_t *info, void *data)
375 /* Check if we are from a forked process that hasn't updated the signal handlers or execed.
376 If so, then we should just quit */
377 if (getpid () != signal_pid)
378 _exit (EXIT_SUCCESS);
380 /* Write signal to main thread, if something goes wrong just close the pipe so it is detected on the other end */
381 if (write (signal_pipe[1], &info->si_signo, sizeof (int)) < 0 ||
382 write (signal_pipe[1], &info->si_pid, sizeof (pid_t)) < 0)
383 close (signal_pipe[1]);
387 handle_signal (GIOChannel *source, GIOCondition condition, gpointer data)
394 if (read (signal_pipe[0], &signo, sizeof (int)) != sizeof (int) ||
395 read (signal_pipe[0], &pid, sizeof (pid_t)) != sizeof (pid_t))
397 g_warning ("Error reading from signal pipe: %s", strerror (errno));
401 g_debug ("Got signal %d from process %d", signo, pid);
403 process = g_hash_table_lookup (processes, GINT_TO_POINTER (pid));
405 process = process_get_current ();
407 g_signal_emit (process, signals[GOT_SIGNAL], 0, signo);
413 process_class_init (ProcessClass *klass)
415 GObjectClass *object_class = G_OBJECT_CLASS (klass);
416 struct sigaction action;
418 klass->stopped = process_stopped;
419 object_class->finalize = process_finalize;
421 g_type_class_add_private (klass, sizeof (ProcessPrivate));
424 g_signal_new (PROCESS_SIGNAL_GOT_DATA,
425 G_TYPE_FROM_CLASS (klass),
427 G_STRUCT_OFFSET (ProcessClass, got_data),
431 signals[GOT_SIGNAL] =
432 g_signal_new (PROCESS_SIGNAL_GOT_SIGNAL,
433 G_TYPE_FROM_CLASS (klass),
435 G_STRUCT_OFFSET (ProcessClass, got_signal),
438 G_TYPE_NONE, 1, G_TYPE_INT);
440 g_signal_new (PROCESS_SIGNAL_STOPPED,
441 G_TYPE_FROM_CLASS (klass),
443 G_STRUCT_OFFSET (ProcessClass, stopped),
448 /* Catch signals and feed them to the main loop via a pipe */
449 processes = g_hash_table_new_full (g_direct_hash, g_direct_equal, NULL, g_object_unref);
450 signal_pid = getpid ();
451 if (pipe (signal_pipe) != 0)
452 g_critical ("Failed to create signal pipe");
453 fcntl (signal_pipe[0], F_SETFD, FD_CLOEXEC);
454 fcntl (signal_pipe[1], F_SETFD, FD_CLOEXEC);
455 g_io_add_watch (g_io_channel_unix_new (signal_pipe[0]), G_IO_IN, handle_signal, NULL);
456 action.sa_sigaction = signal_cb;
457 sigemptyset (&action.sa_mask);
458 action.sa_flags = SA_SIGINFO;
459 sigaction (SIGTERM, &action, NULL);
460 sigaction (SIGINT, &action, NULL);
461 sigaction (SIGHUP, &action, NULL);
462 sigaction (SIGUSR1, &action, NULL);
463 sigaction (SIGUSR2, &action, NULL);