/** * @internal Execute all programs or scripts in a directory. Used when starting * up and shutting down the daemon. * * @param[in] scriptdir Directory to search for executable programs/scripts. * started. * @param arg1 value passed to executed scripts as argument 1. This makes * it possible to handle start and stop in one script */ static void do_scriptdir (const gchar *scriptdir, const gchar *arg1) { GError *err = NULL; GDir *dir; const gchar *f; gchar *argv[3] = {NULL, NULL, NULL}; XMMS_DBG ("Running scripts in %s", scriptdir); if (!g_file_test (scriptdir, G_FILE_TEST_IS_DIR)) { g_mkdir_with_parents (scriptdir, 0755); install_scripts (scriptdir); } dir = g_dir_open (scriptdir, 0, &err); if (!dir) { xmms_log_error ("Could not open script dir '%s' error: %s", scriptdir, err->message); return; } argv[1] = g_strdup (arg1); while ((f = g_dir_read_name (dir))) { argv[0] = g_strdup_printf ("%s/%s", scriptdir, f); if (g_file_test (argv[0], G_FILE_TEST_IS_EXECUTABLE)) { if (!g_spawn_async (g_get_home_dir (), argv, NULL, 0, spawn_script_setup, NULL, NULL, &err)) { xmms_log_error ("Could not run script '%s', error: %s", argv[0], err->message); } } g_free (argv[0]); } g_free (argv[1]); g_dir_close (dir); }
void sendto_callback(GObject *widget, gpointer user_data) { GPtrArray *a; GError *err = NULL; guint i; const char *address, *alias; address = g_object_get_data (widget, "address"); alias = g_object_get_data (widget, "alias"); a = g_ptr_array_new (); g_ptr_array_add (a, "mate-bluetooth-sendto"); if (address != NULL) { char *s; s = g_strdup_printf ("--device=%s", address); g_ptr_array_add (a, s); } if (address != NULL && alias != NULL) { char *s; s = g_strdup_printf ("--name=%s", alias); g_ptr_array_add (a, s); } g_ptr_array_add (a, NULL); if (g_spawn_async(NULL, (char **) a->pdata, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &err) == FALSE) { g_printerr("Couldn't execute command: %s\n", err->message); g_error_free (err); } for (i = 1; a->pdata[i] != NULL; i++) g_free (a->pdata[i]); g_ptr_array_free (a, TRUE); }
void run_plugin(GtkButton* button, gpointer user_data) { FcitxSubConfigWidget* widget = (FcitxSubConfigWidget*) user_data; char *newpath = NULL; char* qtguiwrapper = fcitx_utils_get_fcitx_path_with_filename ("libdir", "fcitx/libexec/fcitx-qt-gui-wrapper"); if (qtguiwrapper) { gchar* argv[4]; argv[0] = qtguiwrapper; argv[1] = "--test"; argv[2] = widget->subconfig->nativepath; argv[3] = 0; int exit_status = 1; g_spawn_sync(NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, &exit_status, NULL); if (exit_status == 0) { gchar* argv2[3]; argv2[0] = qtguiwrapper; argv2[1] = widget->subconfig->nativepath; argv2[2] = 0; g_spawn_async(NULL, argv2, NULL, 0, NULL, NULL, NULL, NULL); free(newpath); } g_free(qtguiwrapper); if (exit_status == 0) { return; } } GtkWidget* dialog = gtk_message_dialog_new (GTK_WINDOW (gtk_widget_get_toplevel (GTK_WIDGET(widget))), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_ERROR, GTK_BUTTONS_CLOSE, "%s", _("Didn't install related component.")); gtk_dialog_run (GTK_DIALOG (dialog)); gtk_widget_destroy (dialog); }
void ProcessLauncher::launchProcess() { GPid pid = 0; int sockets[2]; if (socketpair(AF_UNIX, SOCKET_TYPE, 0, sockets) < 0) { g_printerr("Creation of socket failed: %s.\n", g_strerror(errno)); ASSERT_NOT_REACHED(); return; } String executablePath = m_launchOptions.processType == WebProcess ? executablePathOfWebProcess() : executablePathOfPluginProcess(); CString binaryPath = fileSystemRepresentation(executablePath); GOwnPtr<gchar> socket(g_strdup_printf("%d", sockets[0])); char* argv[3]; argv[0] = const_cast<char*>(binaryPath.data()); argv[1] = socket.get(); argv[2] = 0; GOwnPtr<GError> error; int spawnFlags = G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD; if (!g_spawn_async(0, argv, 0, static_cast<GSpawnFlags>(spawnFlags), childSetupFunction, GINT_TO_POINTER(sockets[1]), &pid, &error.outPtr())) { g_printerr("Unable to fork a new WebProcess: %s.\n", error->message); ASSERT_NOT_REACHED(); } close(sockets[0]); m_processIdentifier = pid; // Monitor the child process, it calls waitpid to prevent the child process from becomming a zombie, // and it allows us to close the socket when the child process crashes. g_child_watch_add(m_processIdentifier, childFinishedFunction, GINT_TO_POINTER(sockets[1])); // We've finished launching the process, message back to the main run loop. RunLoop::main()->dispatch(bind(&ProcessLauncher::didFinishLaunchingProcess, this, m_processIdentifier, sockets[1])); }
static void fixture_setup(TestFixture *fixture, gconstpointer data, gchar **envp) { const gchar *extra_arg = data; GError *error = NULL; gchar *cwd, *path, *cmd, **argv = NULL; fixture->loop = g_main_loop_new(NULL, FALSE); fixture->test_dir = g_strdup("/tmp/qgatest.XXXXXX"); g_assert_nonnull(mkdtemp(fixture->test_dir)); path = g_build_filename(fixture->test_dir, "sock", NULL); cwd = g_get_current_dir(); cmd = g_strdup_printf("%s%cqemu-ga -m unix-listen -t %s -p %s %s %s", cwd, G_DIR_SEPARATOR, fixture->test_dir, path, getenv("QTEST_LOG") ? "-v" : "", extra_arg ?: ""); g_shell_parse_argv(cmd, NULL, &argv, &error); g_assert_no_error(error); g_spawn_async(fixture->test_dir, argv, envp, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &fixture->pid, &error); g_assert_no_error(error); g_child_watch_add(fixture->pid, qga_watch, fixture); fixture->fd = connect_qga(path); g_assert_cmpint(fixture->fd, !=, -1); g_strfreev(argv); g_free(cmd); g_free(cwd); g_free(path); }
static void on_menu_item_activate (CajaMenuItem *menu_item, gpointer data) { CajaShares *shares; CajaFileInfo *info; gchar **args, *dir; GError *error = NULL; info = g_object_get_data (G_OBJECT (menu_item), "file"); shares = g_object_get_data (G_OBJECT (menu_item), "shares"); dir = get_path_from_file_info (info); args = g_new0 (char *, 3); args[0] = g_strdup ("shares-admin"); args[1] = g_strdup_printf ("--add-share=%s", dir); g_spawn_async (NULL, args, NULL, G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_SEARCH_PATH, NULL, NULL, &shares->pid, &error); if (error) { g_warning ("%s", error->message); g_error_free (error); shares->pid = 0; } else { shares->file_info = g_object_ref (info); g_child_watch_add (shares->pid, shares_admin_watch_func, shares); } g_strfreev (args); g_free (dir); }
static void rcd_transaction_check_fs (RCDTransaction *transaction) { char *argv[] = { HELPERDIR "/rcd-statvfs", NULL }; GError *error = NULL; rc_debug (RC_DEBUG_LEVEL_MESSAGE, "Checking for stale mounts..."); time (&transaction->stat_start); g_spawn_async (NULL, argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &transaction->stat_pid, &error); if (error != NULL) { char *msg = g_strdup_printf ("Failed to launch helper: %s", error->message); rc_debug (RC_DEBUG_LEVEL_MESSAGE, msg); g_free (msg); rcd_transaction_transaction (transaction); return; } g_timeout_add (HELPER_TIMEOUT_INTERVAL, (GSourceFunc) rcd_transaction_monitor_cb, transaction); }
static inline int execshssh ( const char *host ) { char **args = NULL; int argsv = 0; helper_parse_setup ( config.ssh_command, &args, &argsv, "{host}", host, NULL ); GError *error = NULL; g_spawn_async ( NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &error ); if ( error != NULL ) { char *msg = g_strdup_printf ( "Failed to execute: 'ssh %s'\nError: '%s'", host, error->message ); error_dialog ( msg, FALSE ); g_free ( msg ); // print error. g_error_free ( error ); } // Free the args list. g_strfreev ( args ); return 0; }
static void _on_icon_run(gpointer data) { DesktopIcon * desktopicon = data; char * argv[] = { NULL, NULL, NULL }; gboolean res; GSpawnFlags flags = G_SPAWN_SEARCH_PATH | G_SPAWN_FILE_AND_ARGV_ZERO; GError * error = NULL; if(desktopicon->confirm != FALSE && _run_confirm(desktopicon) != TRUE) return; if((argv[0] = desktopicon->exec) != NULL || (argv[0] = desktopicon->tryexec) != NULL) /* FIXME it's actually a format string */ res = g_spawn_command_line_async(argv[0], &error); else { argv[0] = desktopicon->path; argv[1] = argv[0]; res = g_spawn_async(NULL, argv, NULL, flags, NULL, NULL, NULL, &error); } if(res != TRUE) desktop_error(desktopicon->desktop, argv[0], 1); /* XXX */ }
static void _settings_on_item_activated(GtkWidget * widget, GtkTreePath * path, gpointer data) { Settings * settings = data; const unsigned int flags = G_SPAWN_FILE_AND_ARGV_ZERO; GtkTreeModel * model; GtkTreeIter iter; gchar * exec; GError * error = NULL; char * argv[] = { "/bin/sh", "sh", "-c", NULL, NULL }; if(_settings_get_iter(settings, &iter, path) == FALSE) return; model = _settings_get_model(settings); gtk_tree_model_get(GTK_TREE_MODEL(model), &iter, SC_EXEC, &exec, -1); # ifdef DEBUG fprintf(stderr, "DEBUG: %s() \"%s\"\n", __func__, exec); # endif argv[3] = exec; if(g_spawn_async(NULL, argv, NULL, flags, NULL, NULL, NULL, &error) == FALSE) _settings_error(error->message, 1); g_free(exec); }
static int _event_mixer_set(Openmoko * openmoko, char const * filename) { int ret = 0; char const scenarios[] = DATADIR "/openmoko/scenarios"; char * pathname; size_t len; char * alsactl[] = { SBINDIR "/alsactl", "alsactl", "-f", NULL, "restore", NULL }; GError * error = NULL; #ifdef DEBUG fprintf(stderr, "DEBUG: %s(\"%s\")\n", __func__, filename); #endif len = sizeof(scenarios) + 1 + strlen(filename); if((pathname = malloc(len)) == NULL) return openmoko->helper->error(NULL, strerror(errno), 1); snprintf(pathname, len, "%s/%s", scenarios, filename); alsactl[3] = pathname; if(g_spawn_async(NULL, alsactl, NULL, G_SPAWN_FILE_AND_ARGV_ZERO, NULL, NULL, NULL, &error) == FALSE) ret = openmoko->helper->error(NULL, error->message, 1); free(pathname); return ret; }
gboolean mu_util_play (const char *path, gboolean allow_local, gboolean allow_remote, GError **err) { gboolean rv; const gchar *argv[3]; const char *prog; g_return_val_if_fail (path, FALSE); g_return_val_if_fail (mu_util_is_local_file (path) || allow_remote, FALSE); g_return_val_if_fail (!mu_util_is_local_file (path) || allow_local, FALSE); prog = g_getenv ("MU_PLAY_PROGRAM"); if (!prog) { #ifdef __APPLE__ prog = "open"; #else prog = "xdg-open"; #endif /*!__APPLE__*/ } argv[0] = prog; argv[1] = path; argv[2] = NULL; err = NULL; rv = g_spawn_async (NULL, (gchar**)&argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, err); return rv; }
static void reconnect_to_parent (MdmDisplay *to) { GError *error; gchar *command_argv[10]; const gchar *proxyreconnect = mdm_daemon_config_get_value_string (MDM_KEY_XDMCP_PROXY_RECONNECT); command_argv[0] = (char *)proxyreconnect; command_argv[1] = "--display"; command_argv[2] = to->parent_disp; command_argv[3] = "--display-authfile"; command_argv[4] = to->parent_auth_file; command_argv[5] = "--to"; command_argv[6] = to->name; command_argv[7] = "--to-authfile"; command_argv[8] = to->authfile; command_argv[9] = NULL; mdm_debug ("XDMCP: migrating display by running " "'%s --display %s --display-authfile %s --to %s --to-authfile %s'", proxyreconnect, to->parent_disp, to->parent_auth_file, to->name, to->authfile); error = NULL; if (!g_spawn_async (NULL, command_argv, NULL, 0, NULL, NULL, NULL, &error)) { mdm_error (_("%s: Failed to run " "'%s --display %s --display-authfile %s --to %s --to-authfile %s': %s"), "mdm_xdmcp_migrate", proxyreconnect, to->parent_disp, to->parent_auth_file, to->name, to->authfile, error->message); g_error_free (error); } }
// launch async scripts one after another static void start_next_script(GPid pid, gint status, GSList *remaining_scripts_to_run) { if(remaining_scripts_to_run) { gboolean ret = False; gchar* full_path = remaining_scripts_to_run->data; gchar *argv[] = { full_path, NULL }; g_debug_inotify ("executing: %s", full_path); if (g_file_test(full_path, G_FILE_TEST_IS_EXECUTABLE )) ret = g_spawn_async("/", argv, NULL, G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, NULL); remaining_scripts_to_run = g_slist_remove(remaining_scripts_to_run, full_path); g_free(full_path); if(!ret) { g_warning("script execution failed or not executable"); start_next_script(0, 0, remaining_scripts_to_run); return; } g_child_watch_add(pid, (GChildWatchFunc)start_next_script, remaining_scripts_to_run); } }
/* panel_helper_suspend */ static void _panel_helper_suspend(Panel * panel) { #ifdef __NetBSD__ int sleep_state = 3; #else int fd; char * suspend[] = { "/usr/bin/sudo", "sudo", "/usr/bin/apm", "-s", NULL }; const unsigned int flags = G_SPAWN_FILE_AND_ARGV_ZERO; GError * error = NULL; #endif #ifdef __NetBSD__ if(sysctlbyname("machdep.sleep_state", NULL, NULL, &sleep_state, sizeof(sleep_state)) != 0) { _panel_helper_error(panel, "sysctl", 1); return; } #else if((fd = open("/sys/power/state", O_WRONLY)) >= 0) { write(fd, "mem\n", 4); close(fd); } else if(g_spawn_async(NULL, geteuid() == 0 ? &suspend[2] : suspend, NULL, geteuid() == 0 ? 0 : flags, NULL, NULL, NULL, &error) != TRUE) { _panel_helper_error(panel, error->message, 1); g_error_free(error); return; } #endif _panel_helper_lock(panel); /* XXX may already be suspended */ }
static void run_notify_command (CutConsoleUI *console, gchar **args) { GError *error = NULL; g_spawn_async(NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &error); if (error) { gchar *command_line; command_line = g_strjoinv(" ", args); g_print("failed to run <%s>: <%s>: <%s>\n", console->notify_command, command_line, error->message); g_free(command_line); g_error_free(error); } }
/* main function */ int main(int argc, char* argv[]) { /* init locale */ setlocale(LC_ALL, ""); bindtextdomain(GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset(GETTEXT_PACKAGE, "UTF-8"); textdomain(GETTEXT_PACKAGE); /* init gtk */ #if !GLIB_CHECK_VERSION(2, 31, 0) g_thread_init(NULL); #endif gdk_threads_init(); gtk_init(&argc, &argv); /* create zathura session */ zathura_t* zathura = zathura_create(); if (zathura == NULL) { return -1; } /* parse command line arguments */ gchar* config_dir = NULL; gchar* data_dir = NULL; gchar* plugin_path = NULL; gchar* loglevel = NULL; gchar* password = NULL; gchar* synctex_editor = NULL; bool forkback = false; bool print_version = false; bool synctex = false; int page_number = ZATHURA_PAGE_NUMBER_UNSPECIFIED; #if (GTK_MAJOR_VERSION == 3) Window embed = 0; #else GdkNativeWindow embed = 0; #endif GOptionEntry entries[] = { { "reparent", 'e', 0, G_OPTION_ARG_INT, &embed, _("Reparents to window specified by xid"), "xid" }, { "config-dir", 'c', 0, G_OPTION_ARG_FILENAME, &config_dir, _("Path to the config directory"), "path" }, { "data-dir", 'd', 0, G_OPTION_ARG_FILENAME, &data_dir, _("Path to the data directory"), "path" }, { "plugins-dir", 'p', 0, G_OPTION_ARG_STRING, &plugin_path, _("Path to the directories containing plugins"), "path" }, { "fork", '\0',0, G_OPTION_ARG_NONE, &forkback, _("Fork into the background"), NULL }, { "password", 'w', 0, G_OPTION_ARG_STRING, &password, _("Document password"), "password" }, { "page", 'P', 0, G_OPTION_ARG_INT, &page_number, _("Page number to go to"), "number" }, { "debug", 'l', 0, G_OPTION_ARG_STRING, &loglevel, _("Log level (debug, info, warning, error)"), "level" }, { "version", 'v', 0, G_OPTION_ARG_NONE, &print_version, _("Print version information"), NULL }, { "synctex", 's', 0, G_OPTION_ARG_NONE, &synctex, _("Enable synctex support"), NULL }, { "synctex-editor-command", 'x', 0, G_OPTION_ARG_STRING, &synctex_editor, _("Synctex editor (forwarded to the synctex command)"), "cmd" }, { NULL, '\0', 0, 0, NULL, NULL, NULL } }; GOptionContext* context = g_option_context_new(" [file1] [file2] [...]"); g_option_context_add_main_entries(context, entries, NULL); GError* error = NULL; if (g_option_context_parse(context, &argc, &argv, &error) == false) { girara_error("Error parsing command line arguments: %s\n", error->message); g_option_context_free(context); g_error_free(error); return -1; } g_option_context_free(context); /* Fork into the background if the user really wants to ... */ if (forkback == true) { int pid = fork(); if (pid > 0) { /* parent */ exit(0); } else if (pid < 0) { /* error */ girara_error("Couldn't fork."); } setsid(); } /* Set log level. */ if (loglevel == NULL || g_strcmp0(loglevel, "info") == 0) { girara_set_debug_level(GIRARA_INFO); } else if (g_strcmp0(loglevel, "warning") == 0) { girara_set_debug_level(GIRARA_WARNING); } else if (g_strcmp0(loglevel, "error") == 0) { girara_set_debug_level(GIRARA_ERROR); } zathura_set_xid(zathura, embed); zathura_set_config_dir(zathura, config_dir); zathura_set_data_dir(zathura, data_dir); zathura_set_plugin_dir(zathura, plugin_path); zathura_set_synctex_editor_command(zathura, synctex_editor); zathura_set_argv(zathura, argv); /* Init zathura */ if(zathura_init(zathura) == false) { girara_error("Could not initialize zathura."); zathura_free(zathura); return -1; } /* Enable/Disable synctex support */ zathura_set_synctex(zathura, synctex); /* Print version */ if (print_version == true) { char* string = zathura_get_version_string(zathura, false); if (string != NULL) { fprintf(stdout, "%s\n", string); } zathura_free(zathura); return 0; } /* open document if passed */ if (argc > 1) { if (page_number > 0) --page_number; document_open_idle(zathura, argv[1], password, page_number); /* open additional files */ for (int i = 2; i < argc; i++) { char* new_argv[] = { *(zathura->global.arguments), argv[i], NULL }; g_spawn_async(NULL, new_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL); } } /* run zathura */ gdk_threads_enter(); gtk_main(); gdk_threads_leave(); /* free zathura */ zathura_free(zathura); return 0; }
gboolean gimp_plug_in_open (GimpPlugIn *plug_in, GimpPlugInCallMode call_mode, gboolean synchronous) { gint my_read[2]; gint my_write[2]; gchar **envp; const gchar *args[9]; gchar **argv; gint argc; gchar *interp, *interp_arg; gchar *read_fd, *write_fd; const gchar *mode; gchar *stm; GError *error = NULL; gboolean debug; guint debug_flag; guint spawn_flags; g_return_val_if_fail (GIMP_IS_PLUG_IN (plug_in), FALSE); g_return_val_if_fail (plug_in->call_mode == GIMP_PLUG_IN_CALL_NONE, FALSE); /* Open two pipes. (Bidirectional communication). */ if ((pipe (my_read) == -1) || (pipe (my_write) == -1)) { gimp_message (plug_in->manager->gimp, NULL, GIMP_MESSAGE_ERROR, "Unable to run plug-in \"%s\"\n(%s)\n\npipe() failed: %s", gimp_object_get_name (plug_in), gimp_filename_to_utf8 (plug_in->prog), g_strerror (errno)); return FALSE; } #if defined(G_WITH_CYGWIN) /* Set to binary mode */ setmode (my_read[0], _O_BINARY); setmode (my_write[0], _O_BINARY); setmode (my_read[1], _O_BINARY); setmode (my_write[1], _O_BINARY); #endif #ifdef G_OS_WIN32 /* Prevent the plug-in from inheriting our ends of the pipes */ SetHandleInformation ((HANDLE) _get_osfhandle (my_read[0]), HANDLE_FLAG_INHERIT, 0); SetHandleInformation ((HANDLE) _get_osfhandle (my_write[1]), HANDLE_FLAG_INHERIT, 0); #endif plug_in->my_read = g_io_channel_unix_new (my_read[0]); plug_in->my_write = g_io_channel_unix_new (my_write[1]); plug_in->his_read = g_io_channel_unix_new (my_write[0]); plug_in->his_write = g_io_channel_unix_new (my_read[1]); g_io_channel_set_encoding (plug_in->my_read, NULL, NULL); g_io_channel_set_encoding (plug_in->my_write, NULL, NULL); g_io_channel_set_encoding (plug_in->his_read, NULL, NULL); g_io_channel_set_encoding (plug_in->his_write, NULL, NULL); g_io_channel_set_buffered (plug_in->my_read, FALSE); g_io_channel_set_buffered (plug_in->my_write, FALSE); g_io_channel_set_buffered (plug_in->his_read, FALSE); g_io_channel_set_buffered (plug_in->his_write, FALSE); g_io_channel_set_close_on_unref (plug_in->my_read, TRUE); g_io_channel_set_close_on_unref (plug_in->my_write, TRUE); g_io_channel_set_close_on_unref (plug_in->his_read, TRUE); g_io_channel_set_close_on_unref (plug_in->his_write, TRUE); /* Remember the file descriptors for the pipes. */ read_fd = g_strdup_printf ("%d", g_io_channel_unix_get_fd (plug_in->his_read)); write_fd = g_strdup_printf ("%d", g_io_channel_unix_get_fd (plug_in->his_write)); switch (call_mode) { case GIMP_PLUG_IN_CALL_QUERY: mode = "-query"; debug_flag = GIMP_DEBUG_WRAP_QUERY; break; case GIMP_PLUG_IN_CALL_INIT: mode = "-init"; debug_flag = GIMP_DEBUG_WRAP_INIT; break; case GIMP_PLUG_IN_CALL_RUN: mode = "-run"; debug_flag = GIMP_DEBUG_WRAP_RUN; break; default: g_assert_not_reached (); } stm = g_strdup_printf ("%d", plug_in->manager->gimp->stack_trace_mode); interp = gimp_interpreter_db_resolve (plug_in->manager->interpreter_db, plug_in->prog, &interp_arg); argc = 0; if (interp) args[argc++] = interp; if (interp_arg) args[argc++] = interp_arg; args[argc++] = plug_in->prog; args[argc++] = "-gimp"; args[argc++] = read_fd; args[argc++] = write_fd; args[argc++] = mode; args[argc++] = stm; args[argc++] = NULL; argv = (gchar **) args; envp = gimp_environ_table_get_envp (plug_in->manager->environ_table); spawn_flags = (G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD | G_SPAWN_CHILD_INHERITS_STDIN); debug = FALSE; if (plug_in->manager->debug) { gchar **debug_argv = gimp_plug_in_debug_argv (plug_in->manager->debug, plug_in->prog, debug_flag, args); if (debug_argv) { debug = TRUE; argv = debug_argv; spawn_flags |= G_SPAWN_SEARCH_PATH; } } /* Fork another process. We'll remember the process id so that we * can later use it to kill the filter if necessary. */ if (! g_spawn_async (NULL, argv, envp, spawn_flags, gimp_plug_in_prep_for_exec, plug_in, &plug_in->pid, &error)) { gimp_message (plug_in->manager->gimp, NULL, GIMP_MESSAGE_ERROR, "Unable to run plug-in \"%s\"\n(%s)\n\n%s", gimp_object_get_name (plug_in), gimp_filename_to_utf8 (plug_in->prog), error->message); g_error_free (error); goto cleanup; } g_io_channel_unref (plug_in->his_read); plug_in->his_read = NULL; g_io_channel_unref (plug_in->his_write); plug_in->his_write = NULL; if (! synchronous) { GSource *source; source = g_io_create_watch (plug_in->my_read, G_IO_IN | G_IO_PRI | G_IO_ERR | G_IO_HUP); g_source_set_callback (source, (GSourceFunc) gimp_plug_in_recv_message, plug_in, NULL); g_source_set_can_recurse (source, TRUE); plug_in->input_id = g_source_attach (source, NULL); g_source_unref (source); } plug_in->open = TRUE; plug_in->call_mode = call_mode; gimp_plug_in_manager_add_open_plug_in (plug_in->manager, plug_in); cleanup: if (debug) g_free (argv); g_free (read_fd); g_free (write_fd); g_free (stm); g_free (interp); g_free (interp_arg); return plug_in->open; }
int open_external_editor(struct tab *t, const char *contents, int (*callback)(const char *, gpointer), gpointer cb_data) { struct stat st; struct external_editor_args *a; GPid pid; char *cmdstr; char filename[PATH_MAX]; char **sv; int fd; int nb, rv; int cnt; if (external_editor == NULL) return (0); snprintf(filename, sizeof filename, "%s" PS "xombreroXXXXXX", temp_dir); /* Create a temporary file */ fd = g_mkstemp(filename); if (fd == -1) { show_oops(t, "Cannot create temporary file"); return (1); } nb = 0; while (contents && nb < strlen(contents)) { if (strlen(contents) - nb > XT_EE_BUFSZ) cnt = XT_EE_BUFSZ; else cnt = strlen(contents) - nb; rv = write(fd, contents+nb, cnt); if (rv < 0) { close(fd); show_oops(t,strerror(errno)); return (1); } nb += rv; } rv = fstat(fd, &st); if (rv == -1) { close(fd); show_oops(t,"Cannot stat file: %s\n", strerror(errno)); return (1); } close(fd); DPRINTF("edit_src: external_editor: %s\n", external_editor); sv = g_strsplit(external_editor, "<file>", -1); cmdstr = g_strjoinv(filename, sv); g_strfreev(sv); sv = g_strsplit_set(cmdstr, " \t", -1); if (!g_spawn_async(NULL, sv, NULL, (G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD), NULL, NULL, &pid, NULL)) { show_oops(t, "%s: could not spawn process"); g_strfreev(sv); g_free(cmdstr); return (1); } g_strfreev(sv); g_free(cmdstr); a = g_malloc(sizeof(struct external_editor_args)); a->child_pid = pid; a->path = g_strdup(filename); a->tab = t; a->mtime = st.st_mtime; a->callback = callback; a->cb_data = cb_data; /* Check every 100 ms if file has changed */ g_timeout_add(100, (GSourceFunc)open_external_editor_cb, (gpointer)a); /* Stop loop child has terminated */ g_child_watch_add(pid, external_editor_closed, (gpointer)a); return (0); }
static void run_tests (const gchar* argv0) { GError *err = NULL; gchar *output = NULL; gchar *erroutput = NULL; gchar *dirname = g_path_get_dirname (argv0); #ifdef G_OS_WIN32 int pipedown[2], pipeup[2]; gchar **argv = 0; gchar spawn_binary[1000] = {0}; gchar full_cmdline[1000] = {0}; g_snprintf (spawn_binary, sizeof (spawn_binary), "%s\\spawn-test-win32-gui.exe", dirname); #endif g_free (dirname); err = NULL; if (!g_spawn_command_line_sync ("nonexistent_application foo 'bar baz' blah blah", NULL, NULL, NULL, &err)) { g_error_free (err); } else { g_warning ("no error for sync spawn of nonexistent application"); exit (1); } err = NULL; if (!g_spawn_command_line_async ("nonexistent_application foo bar baz \"blah blah\"", &err)) { g_error_free (err); } else { g_warning ("no error for async spawn of nonexistent application"); exit (1); } err = NULL; #ifdef G_OS_UNIX if (!g_spawn_command_line_sync ("/bin/sh -c 'echo hello'", &output, NULL, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (output != NULL); if (strcmp (output, "hello\n") != 0) { printf ("output was '%s', should have been 'hello'\n", output); exit (1); } g_free (output); output = NULL; } #endif /* Running sort synchronously, collecting its output. 'sort' command is selected * because it is non-builtin command on both unix and win32 with well-defined stdout behaviour. */ g_file_set_contents ("spawn-test-created-file.txt", "line first\nline 2\nline last\n", -1, &err); g_assert_no_error(err); if (!g_spawn_command_line_sync ("sort spawn-test-created-file.txt", &output, &erroutput, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (output != NULL); g_assert (erroutput != NULL); if (strstr (output, "\nline first") == 0) { printf ("output was '%s', should have contained 'line first' in second line\n", output); exit (1); } if (erroutput[0] != '\0') { printf ("error output was '%s', should have been empty\n", erroutput); exit (1); } g_free (output); output = NULL; g_free (erroutput); erroutput = NULL; g_unlink ("spawn-test-created-file.txt"); } if (!g_spawn_command_line_sync ("sort non-existing-file.txt", NULL, &erroutput, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (erroutput != NULL); if (erroutput[0] == '\0') { printf ("erroutput was empty, expected contain error message about non-existing-file.txt\n"); exit (1); } g_free (erroutput); erroutput = NULL; } #ifdef G_OS_WIN32 printf ("Running spawn-test-win32-gui in various ways.\n"); printf ("First asynchronously (without wait).\n"); g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' 1", spawn_binary); if (!g_spawn_command_line_async (full_cmdline, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } printf ("Now synchronously, collecting its output.\n"); g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' 2", spawn_binary); if (!g_spawn_command_line_sync (full_cmdline, &output, &erroutput, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (output != NULL); g_assert (erroutput != NULL); if (strcmp (output, "This is stdout\r\n") != 0) { printf ("output was '%s', should have been 'This is stdout'\n", g_strescape (output, NULL)); exit (1); } if (strcmp (erroutput, "This is stderr\r\n") != 0) { printf ("error output was '%s', should have been 'This is stderr'\n", g_strescape (erroutput, NULL)); exit (1); } g_free (output); output = NULL; g_free (erroutput); erroutput = NULL; } printf ("Now with G_SPAWN_FILE_AND_ARGV_ZERO.\n"); g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' this-should-be-argv-zero print_argv0", spawn_binary); if (!g_shell_parse_argv (full_cmdline, NULL, &argv, &err)) { fprintf (stderr, "Error parsing command line? %s\n", err->message); g_error_free (err); exit (1); } if (!g_spawn_sync (NULL, argv, NULL, G_SPAWN_FILE_AND_ARGV_ZERO, NULL, NULL, &output, NULL, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { if (strcmp (output, "this-should-be-argv-zero") != 0) { printf ("output was '%s', should have been 'this-should-be-argv-zero'\n", output); exit (1); } g_free (output); output = NULL; } printf ("Now talking to it through pipes.\n"); if (pipe (pipedown) < 0 || pipe (pipeup) < 0) { fprintf (stderr, "Could not create pipes\n"); exit (1); } g_snprintf (full_cmdline, sizeof (full_cmdline), "'%s' pipes %d %d", spawn_binary, pipedown[0], pipeup[1]); if (!g_shell_parse_argv (full_cmdline, NULL, &argv, &err)) { fprintf (stderr, "Error parsing command line? %s\n", err->message); g_error_free (err); exit (1); } if (!g_spawn_async (NULL, argv, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { int k, n; char buf[100]; if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n)) { int errsv = errno; if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errsv)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", (int)sizeof (n), k); exit (1); } if ((k = read (pipeup[0], buf, n)) != n) { int errsv = errno; if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errsv)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", n, k); exit (1); } n = strlen ("Bye then"); if (write (pipedown[1], &n, sizeof (n)) == -1 || write (pipedown[1], "Bye then", n) == -1) { int errsv = errno; fprintf (stderr, "Write error: %s\n", g_strerror (errsv)); exit (1); } if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n)) { int errsv = errno; if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errsv)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", (int)sizeof (n), k); exit (1); } if (n != strlen ("See ya")) { printf ("child wrote %d bytes, expected %d", n, (int) strlen ("See ya")); exit (1); } if ((k = read (pipeup[0], buf, n)) != n) { int errsv = errno; if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errsv)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", n, k); exit (1); } buf[n] = '\0'; if (strcmp (buf, "See ya") != 0) { printf ("output was '%s', should have been 'See ya'\n", buf); exit (1); } } #endif }
static void run_tests (void) { GError *err; gchar *output = NULL; #ifdef G_OS_WIN32 gchar *erroutput = NULL; int pipedown[2], pipeup[2]; gchar **argv = 0; #endif err = NULL; if (!g_spawn_command_line_sync ("nonexistent_application foo 'bar baz' blah blah", NULL, NULL, NULL, &err)) { g_error_free (err); } else { g_warning ("no error for sync spawn of nonexistent application"); exit (1); } err = NULL; if (!g_spawn_command_line_async ("nonexistent_application foo bar baz \"blah blah\"", &err)) { g_error_free (err); } else { g_warning ("no error for async spawn of nonexistent application"); exit (1); } err = NULL; #ifdef G_OS_UNIX if (!g_spawn_command_line_sync ("/bin/sh -c 'echo hello'", &output, NULL, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (output != NULL); if (strcmp (output, "hello\n") != 0) { printf ("output was '%s', should have been 'hello'\n", output); exit (1); } g_free (output); } #else #ifdef G_OS_WIN32 printf ("Running netstat synchronously, collecting its output\n"); if (!g_spawn_command_line_sync ("netstat -n", &output, &erroutput, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (output != NULL); g_assert (erroutput != NULL); if (strstr (output, "Active Connections") == 0) { printf ("output was '%s', should have contained 'Active Connections'\n", output); exit (1); } if (erroutput[0] != '\0') { printf ("error output was '%s', should have been empty\n", erroutput); exit (1); } g_free (output); output = NULL; g_free (erroutput); erroutput = NULL; } printf ("Running spawn-test-win32-gui in various ways. Click on the OK buttons.\n"); printf ("First asynchronously (without wait).\n"); if (!g_spawn_command_line_async ("'.\\spawn-test-win32-gui.exe' 1", &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } printf ("Now synchronously, collecting its output.\n"); if (!g_spawn_command_line_sync ("'.\\spawn-test-win32-gui.exe' 2", &output, &erroutput, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { g_assert (output != NULL); g_assert (erroutput != NULL); if (strcmp (output, "This is stdout\r\n") != 0) { printf ("output was '%s', should have been 'This is stdout'\n", g_strescape (output, NULL)); exit (1); } if (strcmp (erroutput, "This is stderr\r\n") != 0) { printf ("error output was '%s', should have been 'This is stderr'\n", g_strescape (erroutput, NULL)); exit (1); } g_free (output); g_free (erroutput); } printf ("Now with G_SPAWN_FILE_AND_ARGV_ZERO.\n"); if (!g_shell_parse_argv ("'.\\spawn-test-win32-gui.exe' this-should-be-argv-zero nop", NULL, &argv, &err)) { fprintf (stderr, "Error parsing command line? %s\n", err->message); g_error_free (err); exit (1); } if (!g_spawn_async (NULL, argv, NULL, G_SPAWN_FILE_AND_ARGV_ZERO, NULL, NULL, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } printf ("Now talking to it through pipes.\n"); if (pipe (pipedown) < 0 || pipe (pipeup) < 0) { fprintf (stderr, "Could not create pipes\n"); exit (1); } if (!g_shell_parse_argv (g_strdup_printf ("'.\\spawn-test-win32-gui.exe' pipes %d %d", pipedown[0], pipeup[1]), NULL, &argv, &err)) { fprintf (stderr, "Error parsing command line? %s\n", err->message); g_error_free (err); exit (1); } if (!g_spawn_async (NULL, argv, NULL, G_SPAWN_LEAVE_DESCRIPTORS_OPEN | G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, NULL, &err)) { fprintf (stderr, "Error: %s\n", err->message); g_error_free (err); exit (1); } else { int k, n; char buf[100]; if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n)) { if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errno)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", sizeof (n), k); exit (1); } if ((k = read (pipeup[0], buf, n)) != n) { if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errno)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", n, k); exit (1); } n = strlen ("Bye then"); if (write (pipedown[1], &n, sizeof (n)) == -1 || write (pipedown[1], "Bye then", n) == -1) { fprintf (stderr, "Write error: %s\n", g_strerror (errno)); exit (1); } if ((k = read (pipeup[0], &n, sizeof (n))) != sizeof (n)) { if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errno)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", sizeof (n), k); exit (1); } if ((k = read (pipeup[0], buf, n)) != n) { if (k == -1) fprintf (stderr, "Read error: %s\n", g_strerror (errno)); else fprintf (stderr, "Wanted to read %d bytes, got %d\n", n, k); exit (1); } } #endif #endif }
static gboolean GuestInfoVMSupport(RpcInData *data) { #if defined(_WIN32) char vmSupportCmd[] = "vm-support.vbs"; char *vmSupportPath = NULL; gchar *vmSupport = NULL; SECURITY_ATTRIBUTES saProcess = {0}, saThread = {0}; ProcMgr_AsyncProc *vmSupportProc = NULL; ProcMgr_ProcArgs vmSupportProcArgs = {0}; /* * Construct the commandline to be passed during execution * This will be the path of our vm-support.vbs */ vmSupportPath = GuestApp_GetInstallPath(); if (vmSupportPath == NULL) { return RPCIN_SETRETVALS(data, "GuestApp_GetInstallPath failed", FALSE); } /* Put together absolute vm-support filename. */ vmSupport = g_strdup_printf("cscript \"%s%s%s\" -u", vmSupportPath, DIRSEPS, vmSupportCmd); vm_free(vmSupportPath); saProcess.nLength = sizeof saProcess; saProcess.bInheritHandle = TRUE; saThread.nLength = sizeof saThread; vmSupportProcArgs.lpProcessAttributes = &saProcess; vmSupportProcArgs.lpThreadAttributes = &saThread; vmSupportProcArgs.dwCreationFlags = CREATE_NO_WINDOW; g_message("Starting vm-support script - %s\n", vmSupport); vmSupportProc = ProcMgr_ExecAsync(vmSupport, &vmSupportProcArgs); g_free(vmSupport); if (vmSupportProc == NULL) { g_warning("Error starting vm-support script\n"); return RPCIN_SETRETVALS(data, "Error starting vm-support script", FALSE); } ProcMgr_Free(vmSupportProc); return RPCIN_SETRETVALS(data, "", TRUE); #else gchar *vmSupportCmdArgv[] = {"vm-support", "-u", NULL}; g_message("Starting vm-support script - %s\n", vmSupportCmdArgv[0]); if (!g_spawn_async(NULL, vmSupportCmdArgv, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, NULL)) { g_warning("Error starting vm-support script\n"); return RPCIN_SETRETVALS(data, "Error starting vm-support script", FALSE); } return RPCIN_SETRETVALS(data, "", TRUE); #endif }
static void on_new_message(PurpleAccount *account, const char *remote, const char *message) { const char *command = purple_prefs_get_path(PLUGIN_PREF_COMMAND); // the command should be never NULL g_return_if_fail(command); if (!command[0]) { // no command is set return; } const char *protocol = purple_account_get_protocol_name(account); char *local = g_strdup(purple_normalize(account, purple_account_get_username(account))); char *nohtml = purple_markup_strip_html(message); PurpleBuddy *buddy = purple_find_buddy(account, remote); char *icon_encoded = NULL; if (buddy) { // get buddy alias and icon remote = purple_buddy_get_alias(buddy); PurpleBuddyIcon *icon = purple_buddy_get_icon(buddy); if (icon) { size_t len; gconstpointer data = purple_buddy_icon_get_data(icon, &len); icon_encoded = g_base64_encode(data, len); } } char *argv[2]; argv[0] = g_strdup(command); argv[1] = NULL; // prepare child's environment variables char **envp = g_get_environ(); envp = g_environ_setenv(envp, "EVENT_TYPE", "msg", TRUE); envp = g_environ_setenv(envp, "EVENT_NETWORK", protocol, TRUE); envp = g_environ_setenv(envp, "EVENT_LOCAL_USER", local, TRUE); envp = g_environ_setenv(envp, "EVENT_REMOTE_USER", remote, TRUE); if (icon_encoded) envp = g_environ_setenv(envp, "EVENT_REMOTE_USER_ICON", icon_encoded, TRUE); envp = g_environ_setenv(envp, "EVENT_MESSAGE", nohtml, TRUE); envp = g_environ_setenv(envp, "EVENT_MESSAGE_HTML", message, TRUE); // spawn the command GError *err = NULL; if (!g_spawn_async(NULL, argv, envp, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL | G_SPAWN_STDERR_TO_DEV_NULL, NULL, NULL, NULL, &err)) { purple_debug_error("extaction", "%s", err->message); g_clear_error(&err); } // free all resources g_free(argv[0]); g_strfreev(envp); g_free(local); g_free(nohtml); g_free(icon_encoded); }
static char* expand_terminal(char* cmd, gboolean keep_open, GError** error) { FmTerminal* term; const char* opts; char* ret; /* if %s is not found, fallback to -e */ static FmTerminal xterm_def = { .program = "xterm", .open_arg = "-e" }; term = fm_terminal_dup_default(NULL); /* bug #3457335: Crash on application start with Terminal=true. */ if(!term) /* fallback to xterm if a terminal emulator is not found. */ { /* FIXME: we should not hard code xterm here. :-( * It's better to prompt the user and let he or she set * his preferred terminal emulator. */ term = &xterm_def; } if(keep_open && term->noclose_arg) opts = term->noclose_arg; else opts = term->open_arg; if(term->custom_args) ret = g_strdup_printf("%s %s %s %s", term->program, term->custom_args, opts, cmd); else ret = g_strdup_printf("%s %s %s", term->program, opts, cmd); if(term != &xterm_def) g_object_unref(term); return ret; } static gboolean do_launch(GAppInfo* appinfo, const char* full_desktop_path, GKeyFile* kf, GList* gfiles, GAppLaunchContext* ctx, GError** err) { gboolean ret = FALSE; char* cmd, *path; char** argv; int argc; gboolean use_terminal; GAppInfoCreateFlags flags; cmd = expand_exec_macros(appinfo, full_desktop_path, kf, gfiles); if(G_LIKELY(kf)) use_terminal = g_key_file_get_boolean(kf, "Desktop Entry", "Terminal", NULL); else { flags = GPOINTER_TO_UINT(g_object_get_data(G_OBJECT(appinfo), "flags")); use_terminal = (flags & G_APP_INFO_CREATE_NEEDS_TERMINAL) != 0; } if(use_terminal) { /* FIXME: is it right key to mark this option? */ gboolean keep_open = FALSE; char* term_cmd; if(G_LIKELY(kf)) keep_open = g_key_file_get_boolean(kf, "Desktop Entry", "X-KeepTerminal", NULL); term_cmd = expand_terminal(cmd, keep_open, err); g_free(cmd); if(!term_cmd) return FALSE; cmd = term_cmd; } g_debug("launch command: <%s>", cmd); if(g_shell_parse_argv(cmd, &argc, &argv, err)) { struct ChildSetup data; if(ctx) { gboolean use_sn; if(G_LIKELY(kf) && g_key_file_has_key(kf, "Desktop Entry", "StartupNotify", NULL)) use_sn = g_key_file_get_boolean(kf, "Desktop Entry", "StartupNotify", NULL); else if(fm_config->force_startup_notify) { /* if the app doesn't explicitly ask us not to use sn, * and fm_config->force_startup_notify is TRUE, then * use it by default, unless it's a console app. */ use_sn = !use_terminal; /* we only use sn for GUI apps by default */ /* FIXME: console programs should use sn_id of terminal emulator instead. */ } else use_sn = FALSE; data.display = g_app_launch_context_get_display(ctx, appinfo, gfiles); if(use_sn) data.sn_id = g_app_launch_context_get_startup_notify_id(ctx, appinfo, gfiles); else data.sn_id = NULL; } else { data.display = NULL; data.sn_id = NULL; } g_debug("sn_id = %s", data.sn_id); if(G_LIKELY(kf)) path = g_key_file_get_string(kf, "Desktop Entry", "Path", NULL); else path = NULL; ret = g_spawn_async(path, argv, NULL, G_SPAWN_SEARCH_PATH, child_setup, &data, NULL, err); g_free(path); g_free(data.display); g_free(data.sn_id); g_strfreev(argv); } g_free(cmd); return ret; }
int PrintText(const char *name, gchar *str) { gchar *cmd = GetString("Print", "Command", "lpr"); GError *error = NULL; gchar *filename = NULL; GPid pid = 0; gchar *argv[3]; gchar tmpname[20]; Trace("Running comand %s\n%s",cmd,str); do { g_free(filename); g_snprintf(tmpname,19,"%08lx.tmp",rand() ^ ((unsigned long) time(0))); filename = g_build_filename(g_get_tmp_dir(),tmpname,NULL); } while(g_file_test(filename,G_FILE_TEST_EXISTS)); Trace("Temporary file: %s",filename); if(!g_file_set_contents(filename,str,-1,&error)) { if(error) { Warning( N_( "Can't create temporary file:\n%s" ), error->message ? error->message : N_( "Unexpected error" )); g_error_free(error); } remove(filename); g_free(filename); g_error_free(error); g_free(cmd); return -1; } argv[0] = (gchar *) cmd; argv[1] = filename; argv[2] = NULL; Trace("Spawning %s %s",cmd,filename); error = NULL; if(!g_spawn_async( NULL, // const gchar *working_directory, argv, // gchar **argv, NULL, // gchar **envp, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, // GSpawnFlags flags, NULL, // GSpawnChildSetupFunc child_setup, NULL, // gpointer user_data, &pid, // GPid *child_pid, &error )) // GError **error); { if(error) { Warning( N_( "Error spawning %s\n%s" ), argv[0], error->message ? error->message : N_( "Unexpected error" )); g_error_free(error); } remove(filename); g_free(filename); g_free(cmd); return -1; } g_free(cmd); Trace("pid %d",(int) pid); g_child_watch_add(pid,(GChildWatchFunc) print_finished,filename); return 0; }
static void infinoted_plugin_autosave_save(InfinotedPluginAutosaveSessionInfo* info) { InfdDirectory* directory; InfBrowserIter* iter; GError* error; gchar* path; InfSession* session; InfBuffer* buffer; gchar* root_directory; gchar* argv[4]; directory = infinoted_plugin_manager_get_directory(info->plugin->manager); iter = &info->iter; error = NULL; if(info->timeout != NULL) { inf_io_remove_timeout(infd_directory_get_io(directory), info->timeout); info->timeout = NULL; } g_object_get(G_OBJECT(info->proxy), "session", &session, NULL); buffer = inf_session_get_buffer(session); inf_signal_handlers_block_by_func( G_OBJECT(buffer), G_CALLBACK(infinoted_plugin_autosave_buffer_notify_modified_cb), info ); if(infd_directory_iter_save_session(directory, iter, &error) == FALSE) { path = inf_browser_get_path(INF_BROWSER(directory), iter); infinoted_log_warning( infinoted_plugin_manager_get_log(info->plugin->manager), _("Failed to auto-save session \"%s\": %s\n\n" "Will retry in %u seconds."), path, error->message, info->plugin->interval ); g_free(path); g_error_free(error); error = NULL; infinoted_plugin_autosave_start(info); } else { /* TODO: Remove this as soon as directory itself unsets modified flag * on session_write */ inf_buffer_set_modified(INF_BUFFER(buffer), FALSE); if(info->plugin->hook != NULL) { path = inf_browser_get_path(INF_BROWSER(directory), iter); g_object_get( G_OBJECT(infd_directory_get_storage(directory)), "root-directory", &root_directory, NULL ); argv[0] = info->plugin->hook; argv[1] = root_directory; argv[2] = path; argv[3] = NULL; if(!g_spawn_async(NULL, argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &error)) { infinoted_log_warning( infinoted_plugin_manager_get_log(info->plugin->manager), _("Could not execute autosave hook: \"%s\""), error->message ); g_error_free(error); error = NULL; } g_free(path); g_free(root_directory); } } inf_signal_handlers_unblock_by_func( G_OBJECT(buffer), G_CALLBACK(infinoted_plugin_autosave_buffer_notify_modified_cb), info ); g_object_unref(session); }
gboolean cd_clock_update_with_time (GldiModuleInstance *myApplet) { CD_APPLET_ENTER; //\________________ On recupere l'heure courante. time_t epoch = (time_t) time (NULL); _get_current_time (epoch, myApplet); //\________________ On change la date si necessaire. int iWidth, iHeight; CD_APPLET_GET_MY_ICON_EXTENT (&iWidth, &iHeight); gboolean bNewDate = (myData.currentTime.tm_mday != myData.iLastCheckedDay || myData.currentTime.tm_mon != myData.iLastCheckedMonth || myData.currentTime.tm_year != myData.iLastCheckedYear); if (bNewDate) { strftime (s_cDateBuffer, CD_CLOCK_DATE_BUFFER_LENGTH, "%a %d %b", &myData.currentTime); myData.iLastCheckedDay = myData.currentTime.tm_mday; myData.iLastCheckedMonth = myData.currentTime.tm_mon; myData.iLastCheckedYear = myData.currentTime.tm_year; } if (CD_APPLET_MY_CONTAINER_IS_OPENGL && myConfig.bOldStyle && myConfig.iShowDate == CAIRO_DOCK_INFO_ON_ICON) { if (bNewDate || myData.iDateTexture == 0) { if (myData.iDateTexture != 0) _cairo_dock_delete_texture (myData.iDateTexture); double fScale = (double) iWidth / (double) myData.DimensionData.width; GldiTextDescription labelDescription; memset (&labelDescription, 0, sizeof (GldiTextDescription)); gldi_text_description_set_font (&labelDescription, (gchar*)"Sans 8"); // casted and then set to null labelDescription.fColorStart.rgba.red = myConfig.fDateColor[0]; labelDescription.fColorStart.rgba.green = myConfig.fDateColor[1]; labelDescription.fColorStart.rgba.blue = myConfig.fDateColor[2]; labelDescription.fColorStart.rgba.alpha = 1.; labelDescription.bNoDecorations = TRUE; cairo_surface_t *pDateSurface = cairo_dock_create_surface_from_text_full (s_cDateBuffer, &labelDescription, fScale, iWidth, &myData.iDateWidth, &myData.iDateHeight); //g_print ("date : %dx%d\n", myData.iDateWidth, myData.iDateHeight); myData.iDateTexture = cairo_dock_create_texture_from_surface (pDateSurface); cairo_surface_destroy (pDateSurface); labelDescription.cFont = NULL; gldi_text_description_reset (&labelDescription); } } if (bNewDate && myConfig.iShowDate == CAIRO_DOCK_INFO_ON_LABEL) { CD_APPLET_SET_NAME_FOR_MY_ICON (s_cDateBuffer); } //\________________ On dessine avec cette heure. myData.iSmoothAnimationStep = 0; if (myConfig.bOldStyle) { if (CD_APPLET_MY_CONTAINER_IS_OPENGL) cd_clock_render_analogic_to_texture (myApplet, iWidth, iHeight, &myData.currentTime, 0.); else cd_clock_draw_analogic (myApplet, iWidth, iHeight, &myData.currentTime); } else { cd_clock_draw_text (myApplet, iWidth, iHeight, &myData.currentTime); ///if (CD_APPLET_MY_CONTAINER_IS_OPENGL) // on ne sait pas bien dessiner du texte, donc on le fait en cairo, et on transfere tout sur notre texture. /// cairo_dock_update_icon_texture (myIcon); } ///CD_APPLET_REDRAW_MY_ICON; //\________________ On teste les alarmes et les taches. if (!myConfig.bShowSeconds || myData.currentTime.tm_min != myData.iLastCheckedMinute) // un g_timeout de 1min ne s'effectue pas forcement a exectement 1 minute d'intervalle, et donc pourrait "sauter" la minute de l'alarme, d'ou le test sur bShowSeconds dans le cas ou l'applet ne verifie que chaque minute. { myData.iLastCheckedMinute = myData.currentTime.tm_min; // les alarmes. CDClockAlarm *pAlarm; guint i; for (i = 0; i < myConfig.pAlarms->len; i ++) { pAlarm = g_ptr_array_index (myConfig.pAlarms, i); if (myData.currentTime.tm_hour == pAlarm->iHour && myData.currentTime.tm_min == pAlarm->iMinute) { gboolean bShowAlarm = FALSE, bRemoveAlarm = FALSE; if (pAlarm->iDayOfWeek > 0) { if (pAlarm->iDayOfWeek == 1) bShowAlarm = TRUE; else if (pAlarm->iDayOfWeek - 1 == myData.currentTime.tm_wday) bShowAlarm = TRUE; else if (myData.currentTime.tm_wday == 0 || myData.currentTime.tm_wday == 6) // week-end { if (pAlarm->iDayOfWeek == 9) bShowAlarm = TRUE; } else if (pAlarm->iDayOfWeek == 8) bShowAlarm = TRUE; } else if (pAlarm->iDayOfMonth > 0) bShowAlarm = (pAlarm->iDayOfMonth - 1 == myData.currentTime.tm_mday); else // c'est une alarme qui ne se repete pas. { bShowAlarm = TRUE; bRemoveAlarm = TRUE; } if (bShowAlarm) { cd_message ("Dring ! %s", pAlarm->cMessage); gldi_dialog_show_temporary (pAlarm->cMessage, myIcon, myContainer, 60e3); if (pAlarm->cCommand != NULL) { if (myData.iAlarmPID > 0) { kill (myData.iAlarmPID, 1); myData.iAlarmPID = 0; } GError *erreur = NULL; gchar **argv = g_strsplit (pAlarm->cCommand, " ", -1); g_spawn_async (NULL, argv, NULL, 0, NULL, NULL, &myData.iAlarmPID, &erreur); if (erreur != NULL) { cd_warning ("clock : when trying to execute '%s' : %s", pAlarm->cCommand, erreur->message); g_error_free (erreur); myData.iAlarmPID = 0; } g_strfreev (argv); cd_message (" --> child_pid : %d", myData.iAlarmPID); } } if (bRemoveAlarm) { cd_message ("Cette alarme ne sera pas repetee"); g_ptr_array_remove_index (myConfig.pAlarms, i); cd_clock_free_alarm (pAlarm); /// A FAIRE : effacer l'heure dans le fichier de conf pour cette alarme. } } } // display missed tasks. if (!myData.bTaskCheckedOnce) { myData.bTaskCheckedOnce = TRUE; myData.pMissedTasks = cd_clock_get_missed_tasks (myApplet); } if (myData.pMissedTasks != NULL) // so if the dialog was closed before we could acknowledge all the tasks, it will re-open. { CDClockTask *pTask = myData.pMissedTasks->data; gchar *cMessage = _make_missed_task_message (pTask, myApplet); CairoDialogAttr attr; memset (&attr, 0, sizeof (CairoDialogAttr)); attr.cText = cMessage; attr.bUseMarkup = TRUE; attr.cImageFilePath = (gchar *)MY_APPLET_SHARE_DATA_DIR"/icon-task.png"; const gchar *cButtonsImage[3] = {"ok", NULL, NULL}; if (myData.pMissedTasks->next != NULL) { cButtonsImage[0] = "cancel"; cButtonsImage[1] = "next.png"; } attr.cButtonsImage = cButtonsImage; attr.pActionFunc = (CairoDockActionOnAnswerFunc)_on_next_missed_task; attr.pUserData = myApplet; attr.pFreeDataFunc = NULL; attr.iTimeLength = 0; attr.pIcon = myIcon; attr.pContainer = myContainer; gldi_dialog_new (&attr); g_free (cMessage); } // display next task. if (myData.pNextTask != NULL) { //g_print ("next task : %s\n", myData.pNextTask->cTitle); struct tm st; st.tm_min = myData.pNextTask->iMinute; st.tm_hour = myData.pNextTask->iHour; st.tm_mday = myData.pNextTask->iDay; st.tm_mon = myData.pNextTask->iMonth; st.tm_year = myData.pNextTask->iYear - 1900; st.tm_sec = 0; st.tm_isdst = myData.currentTime.tm_isdst; time_t t = mktime (&st); //g_print ("time : %ld, task : %ld\n", epoch, t); if (t < epoch) // la tache est depassee. { // acknowledge this task myData.pNextTask->bAcknowledged = TRUE; myData.pBackend->update_task (myData.pNextTask, myApplet); // look for next task. myData.pNextTask = cd_clock_get_next_scheduled_task (myApplet); } else if (t < epoch + 15*60 && t >= epoch) { if (t < epoch + 60) { if (! myData.pNextTask->bFirstWarning) { //g_print ("first warning\n"); myData.pNextTask->bFirstWarning = TRUE; gchar *cText = g_strdup_printf ("%s\n<b>%s</b>\n %s\n\n%s", D_("It's time for the following task:"), myData.pNextTask->cTitle?myData.pNextTask->cTitle:D_("No title"), myData.pNextTask->cText?myData.pNextTask->cText:"", D_("Repeat this message every:")); _task_warning (myData.pNextTask, cText); g_free (cText); } } else if (! myData.pNextTask->b15mnWarning) { //g_print ("15 mn warning\n"); myData.pNextTask->b15mnWarning = TRUE; gchar *cText = g_strdup_printf ("%s\n<b>%s</b>\n %s", D_("This task will begin in 15 minutes:"), myData.pNextTask->cTitle?myData.pNextTask->cTitle:D_("No title"), myData.pNextTask->cText?myData.pNextTask->cText:""); CairoDialogAttr attr; memset (&attr, 0, sizeof (CairoDialogAttr)); attr.cText = (gchar *)cText; attr.cImageFilePath = (gchar *)MY_APPLET_SHARE_DATA_DIR"/icon-task.png"; attr.iTimeLength = 60e3; attr.bUseMarkup = TRUE; attr.pIcon = myIcon; attr.pContainer = myContainer; gldi_dialog_new (&attr); CD_APPLET_DEMANDS_ATTENTION (NULL, 60); } } // display next anniversary if it is scheduled in less than 1 day, because anniversary require time to prepare. if (myData.pNextAnniversary != NULL) { if (!myData.pNextAnniversary->b1DayWarning && ! myData.pNextAnniversary->bFirstWarning && ! myData.pNextAnniversary->b15mnWarning) { GDate* pCurrentDate = g_date_new_dmy (myData.currentTime.tm_mday, myData.currentTime.tm_mon + 1, myData.currentTime.tm_year+1900); GDate* pAnnivDate = g_date_new_dmy (myData.pNextAnniversary->iDay, myData.pNextAnniversary->iMonth + 1, myData.currentTime.tm_year+1900); gint iDaysToNextAnniversary = g_date_days_between (pCurrentDate, pAnnivDate); if (iDaysToNextAnniversary >= 0 && iDaysToNextAnniversary <= 1) { myData.pNextAnniversary->b1DayWarning = TRUE; gchar *cText = g_strdup_printf ("%s\n<b>%s</b>\n %s\n\n%s", iDaysToNextAnniversary == 0 ? D_("Today is the following anniversary:") : D_("Tomorrow is the following anniversary:"), myData.pNextTask->cTitle?myData.pNextTask->cTitle:D_("No title"), myData.pNextTask->cText?myData.pNextTask->cText:"", D_("Repeat this message every:")); _task_warning (myData.pNextTask, cText); g_free (cText); myData.pNextAnniversary = cd_clock_get_next_anniversary (myApplet); } g_date_free (pCurrentDate); g_date_free (pAnnivDate); } } } } CD_APPLET_LEAVE(TRUE); }
gboolean hald_runner_start_runner(void) { DBusServer *server = NULL; DBusError err; GError *error = NULL; GPid pid; char *argv[] = { NULL, NULL}; char *env[] = { NULL, NULL, NULL, NULL}; const char *hald_runner_path; char *server_addr; running_processes = g_hash_table_new (g_direct_hash, g_direct_equal); dbus_error_init(&err); server = dbus_server_listen(DBUS_SERVER_ADDRESS, &err); if (server == NULL) { HAL_ERROR (("Cannot create D-BUS server for the runner")); goto error; } dbus_server_setup_with_g_main(server, NULL); dbus_server_set_new_connection_function(server, handle_connection, NULL, NULL); argv[0] = "hald-runner"; server_addr = dbus_server_get_address (server); env[0] = g_strdup_printf("HALD_RUNNER_DBUS_ADDRESS=%s", server_addr); dbus_free (server_addr); hald_runner_path = g_getenv("HALD_RUNNER_PATH"); if (hald_runner_path != NULL) { env[1] = g_strdup_printf ("PATH=%s:" PACKAGE_LIBEXEC_DIR ":" PACKAGE_SCRIPT_DIR ":" PACKAGE_BIN_DIR, hald_runner_path); } else { env[1] = g_strdup_printf ("PATH=" PACKAGE_LIBEXEC_DIR ":" PACKAGE_SCRIPT_DIR ":" PACKAGE_BIN_DIR); } /*env[2] = "DBUS_VERBOSE=1";*/ if (!g_spawn_async(NULL, argv, env, G_SPAWN_DO_NOT_REAP_CHILD|G_SPAWN_SEARCH_PATH, NULL, NULL, &pid, &error)) { HAL_ERROR (("Could not spawn runner : '%s'", error->message)); g_error_free (error); goto error; } g_free(env[0]); g_free(env[1]); HAL_INFO (("Runner has pid %d", pid)); g_child_watch_add(pid, runner_died, NULL); while (runner_connection == NULL) { /* Wait for the runner */ g_main_context_iteration(NULL, TRUE); } return TRUE; error: if (server != NULL) dbus_server_unref(server); return FALSE; }
gboolean csm_process_helper (const char *command_line, unsigned int timeout, GError **error) { CsmProcessHelper *helper; gchar **argv = NULL; GPid pid; gboolean ret; if (!g_shell_parse_argv (command_line, NULL, &argv, error)) return FALSE; ret = g_spawn_async (NULL, argv, NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, error); g_strfreev (argv); if (!ret) return FALSE; ret = FALSE; helper = g_slice_new0 (CsmProcessHelper); helper->command_line = command_line; helper->pid = pid; helper->timed_out = FALSE; helper->status = -1; helper->loop = g_main_loop_new (NULL, FALSE); helper->child_id = g_child_watch_add (helper->pid, on_child_exited, helper); helper->timeout_id = g_timeout_add (timeout, on_child_timeout, helper); g_main_loop_run (helper->loop); if (helper->timed_out) { g_set_error_literal (error, G_IO_CHANNEL_ERROR, G_IO_CHANNEL_ERROR_FAILED, "Timed out"); } else { if (g_spawn_check_exit_status (helper->status, error)) ret = TRUE; } if (helper->loop) { g_main_loop_unref (helper->loop); helper->loop = NULL; } if (helper->child_id) { g_source_remove (helper->child_id); helper->child_id = 0; } if (helper->timeout_id) { g_source_remove (helper->timeout_id); helper->timeout_id = 0; } g_slice_free (CsmProcessHelper, helper); return ret; }
int pg_util_spawn_qemu(const char *socket_path_0, const char *socket_path_1, const char *mac_0, const char *mac_1, const char *vm_image_path, const char *vm_key_path, const char *hugepages_path, struct pg_error **errp) { int child_pid = 0; static uint16_t vm_id; gchar **argv = NULL; gchar *argv_qemu = NULL; gchar *argv_sock_0 = NULL; gchar *argv_sock_1 = NULL; gchar *ssh_cmd = NULL; GError *error = NULL; g_assert(g_file_test(socket_path_0, G_FILE_TEST_EXISTS)); g_assert(g_file_test(socket_path_1, G_FILE_TEST_EXISTS)); g_assert(g_file_test(vm_image_path, G_FILE_TEST_EXISTS)); g_assert(g_file_test(vm_key_path, G_FILE_TEST_EXISTS)); g_assert(g_file_test(hugepages_path, G_FILE_TEST_EXISTS)); if (socket_path_0) { argv_sock_0 = g_strdup_printf("%s%s%s%s%s%s", " -chardev socket,id=char0,path=", socket_path_0, " -netdev type=vhost-user,id=mynet0,chardev=char0,vhostforce", " -device virtio-net-pci,mac=", mac_0, ",netdev=mynet0"); } if (socket_path_1) { argv_sock_1 = g_strdup_printf("%s%s%s%s%s%s", " -chardev socket,id=char1,path=", socket_path_1, " -netdev type=vhost-user,id=mynet1,chardev=char1,vhostforce", " -device virtio-net-pci,mac=", mac_1, ",netdev=mynet1"); } argv_qemu = g_strdup_printf( "%s%s%u%s%s%s%s%s%s%s%s%u%s%s%s%s", "qemu-system-x86_64 -m 512M -enable-kvm", " -vnc :", vm_id, " -nographic -snapshot -object", " memory-backend-file,id=mem,size=512M,mem-path=", hugepages_path, ",share=on", " -numa node,memdev=mem -mem-prealloc", " -drive file=", vm_image_path, " -redir tcp:", vm_id + 65000, "::22", " -netdev user,id=network0 -device e1000,netdev=network0", argv_sock_0, argv_sock_1); argv = g_strsplit(argv_qemu, " ", 0); g_assert(g_spawn_async(NULL, argv, NULL, (GSpawnFlags) G_SPAWN_SEARCH_PATH | G_SPAWN_DO_NOT_REAP_CHILD, (GSpawnChildSetupFunc) NULL, NULL, &child_pid, &error)); g_assert(!error); ssh_cmd = g_strdup_printf("%s%s%s%u%s%s%s", "ssh root@localhost -q -i ", vm_key_path, " -p ", vm_id + 65000, " -oConnectTimeout=1 ", "-oStrictHostKeyChecking=no ", "ls"); if (pg_util_cmdloop(ssh_cmd, 10 * 60)) *errp = pg_error_new("qemu spawn failed"); vm_id++; g_free(argv_qemu); g_free(argv_sock_0); g_free(argv_sock_1); g_free(ssh_cmd); g_strfreev(argv); return child_pid; }