static void shell_action_handle_uris_cb (GSimpleAction *action, GVariant *parameter, EShell *shell) { const gchar **uris; gchar *change_dir = NULL; gint ii; /* Do not use g_strfreev() here. */ uris = g_variant_get_strv (parameter, NULL); if (uris && g_strcmp0 (uris[0], "--use-cwd") == 0 && uris[1] && *uris[1]) { change_dir = g_get_current_dir (); if (g_chdir (uris[1]) != 0) g_warning ("%s: Failed to change directory to '%s': %s", G_STRFUNC, uris[1], g_strerror (errno)); for (ii = 0; uris[ii + 2]; ii++) { uris[ii] = uris[ii + 2]; } uris[ii] = NULL; } e_shell_handle_uris (shell, uris, FALSE); g_free (uris); if (change_dir) { if (g_chdir (change_dir) != 0) g_warning ("%s: Failed to return back to '%s': %s", G_STRFUNC, change_dir, g_strerror (errno)); g_free (change_dir); } }
static GObject * get_toplevel_from_string (GladePreviewer *app, gchar *name, gchar *string, gsize size) { gchar *wd = NULL; GObject *retval; /* We need to change the working directory so builder get a chance to load resources */ if (app->file_name) { gchar *dirname = g_path_get_dirname (app->file_name); wd = g_get_current_dir (); g_chdir (dirname); g_free (dirname); } /* We use template flag as a hint since the user can turn on and off template * while the preview is live. */ retval = (app->is_template) ? glade_preview_template_object_new (string, size) : NULL; if (!retval) { GtkBuilder *builder = gtk_builder_new (); GError *error = NULL; /* We do not know if its a template yet */ app->is_template = FALSE; if (gtk_builder_add_from_string (builder, string, size, &error)) retval = get_toplevel (builder, name); else { if (error->code == GTK_BUILDER_ERROR_UNHANDLED_TAG && (retval = glade_preview_template_object_new (string, size))) { /* At this point we know it is a template, so keep a hint for next time */ app->is_template = TRUE; } else { gchar *message = g_strdup_printf (_("Couldn't load builder definition: %s"), error->message); glade_preview_window_set_message (app->window, GTK_MESSAGE_ERROR, message); g_free (message); } g_error_free (error); } g_object_unref (builder); } /* restore directory */ if (wd) { g_chdir (wd); g_free (wd); } return retval; }
static void cd_binarydir (const char *argv0) { gchar *dir = g_path_get_dirname (argv0); g_warn_if_fail (g_chdir (dir) == 0); g_free (dir); }
int main (int argc, char *argv[]) { GtkBuilder *builder; GtkWidget *win; #ifdef GTK_SRCDIR g_chdir (GTK_SRCDIR); #endif gtk_init (); builder = gtk_builder_new (); gtk_builder_add_callback_symbol (builder, "back_to_main", G_CALLBACK (back_to_main)); gtk_builder_add_callback_symbol (builder, "go_to_secondary", G_CALLBACK (go_to_secondary)); gtk_builder_add_from_file (builder, "teststackedheaders.ui", NULL); gtk_builder_connect_signals (builder, NULL); win = (GtkWidget *)gtk_builder_get_object (builder, "window"); header_stack = (GtkWidget *)gtk_builder_get_object (builder, "header_stack"); page_stack = (GtkWidget *)gtk_builder_get_object (builder, "page_stack"); gtk_window_present (GTK_WINDOW (win)); gtk_main (); return 0; }
bool M_SetCurrentFolder(const char *path) { int res = g_chdir(path); if (res == -1) { set_file_error_from_errno(); return false; } return true; }
SludgeApplication::~SludgeApplication() { if (currentFolder[0] != 0) { if (g_chdir(g_get_user_config_dir())) return; #ifdef __WIN32 _mkdir("sludge-devkit"); #else g_mkdir("sludge-devkit", 0000777); #endif if (g_chdir("sludge-devkit")) return; FILE * fp = fopen (configfile, "w"); if (fp) { fprintf (fp, "%s\n", currentFolder); fclose (fp); } } }
gboolean i_daemon (gboolean nochdir, gboolean noclose) { pid_t pid; pid = fork(); if (pid > 0) { _exit(0); } else if (pid == -1) { return FALSE; } if (setsid() == -1) { return FALSE; } if (!nochdir) { if (g_chdir("/") == -1) { return FALSE; } } if (!noclose) { gint fd; fd = open("/dev/null", O_RDWR); if (fd == -1) { return FALSE; } if (dup2(fd, STDIN_FILENO) == -1 || dup2(fd, STDOUT_FILENO) == -1 || dup2(fd, STDERR_FILENO) == -1) { return FALSE; } if (fd > 2) { close(fd); } } return TRUE; }
void SludgeProjectManager::saveIniFile() { if (g_chdir(g_get_user_config_dir())) return; #ifdef __WIN32 _mkdir("sludge-devkit"); #else g_mkdir("sludge-devkit", 0000777); #endif g_chdir("sludge-devkit"); FILE * fp = fopen("SLUDGE.ini", "wb"); fprintf(fp, "KillImages=%d\x0D\x0A", programSettings.compilerKillImages); fprintf(fp, "WriteStrings=%d\x0D\x0A", programSettings.compilerWriteStrings); fprintf(fp, "Verbose=%d\x0D\x0A", programSettings.compilerVerbose); fprintf(fp, "SearchSensitive=%d\x0D\x0A", programSettings.searchSensitive); fprintf(fp, "Editor=%s\x0D\x0A", editor); fprintf(fp, "ImageViewer=%s\x0D\x0A", imageViewer); fprintf(fp, "AudioPlayer=%s\x0D\x0A", audioPlayer); fprintf(fp, "ModPlayer=%s\x0D\x0A", modPlayer); fclose(fp); g_chdir(workingDir); }
//LOGGER USER QUERIES int create_dir() { char tek_day_dir[ 11 ]; GDate *date = g_date_new(); const time_t timestamp = time( NULL ); g_date_set_time_t( date, timestamp ); if( g_mkdir_with_parents( PATH_TO_LOG_USER_QUERIES, 0755 ) == 0 ) { if( g_chdir( PATH_TO_LOG_USER_QUERIES ) == 0 ) { sprintf( tek_day_dir, "%d-%d-%d", g_date_get_year( date ), g_date_get_month( date ), g_date_get_day( date ) ); if( g_mkdir_with_parents( tek_day_dir, 0755 ) == 0 ) { g_date_free( date ); if( g_chdir( tek_day_dir ) == 0 ) return 1; } } } g_date_free( date ); return 0; }
gboolean a_file_save ( VikAggregateLayer *top, gpointer vp, const gchar *filename ) { FILE *f; if (strncmp(filename, "file://", 7) == 0) filename = filename + 7; f = g_fopen(filename, "w"); if ( ! f ) return FALSE; // Enable relative paths in .vik files to work gchar *cwd = g_get_current_dir(); gchar *dir = g_path_get_dirname ( filename ); if ( dir ) { if ( g_chdir ( dir ) ) { g_warning ( "Could not change directory to %s", dir ); } g_free (dir); } file_write ( top, f, vp ); // Restore previous working directory if ( cwd ) { if ( g_chdir ( cwd ) ) { g_warning ( "Could not return to directory %s", cwd ); } g_free (cwd); } fclose(f); f = NULL; return TRUE; }
int main(int argc, char** argv) { SoupServer* server; SoupURI* soup_uri; g_thread_init(NULL); gtk_test_init(&argc, &argv, NULL); /* Hopefully make test independent of the path it's called from. */ while (!g_file_test ("WebKit/gtk/tests/resources/test.html", G_FILE_TEST_EXISTS)) { char path_name[PATH_MAX]; g_chdir(".."); g_assert(!g_str_equal(getcwd(path_name, PATH_MAX), "/")); } g_chdir("WebKit/gtk/tests/resources/"); server = soup_server_new(SOUP_SERVER_PORT, 0, NULL); soup_server_run_async(server); soup_server_add_handler(server, NULL, server_callback, NULL, NULL); soup_uri = soup_uri_new("http://127.0.0.1/"); soup_uri_set_port(soup_uri, soup_server_get_port(server)); base_uri = soup_uri_to_string(soup_uri, FALSE); soup_uri_free(soup_uri); g_test_bug_base("https://bugs.webkit.org/"); g_test_add_func("/webkit/webview/icon-uri", test_webkit_web_view_icon_uri); g_test_add_func("/webkit/webview/adjustments", test_webkit_web_view_adjustments); return g_test_run (); }
static void prepare_unmount(GMount* mount) { /* ensure that CWD is not on the mounted filesystem. */ char* cwd_str = g_get_current_dir(); GFile* cwd = g_file_new_for_path(cwd_str); GFile* root = g_mount_get_root(mount); g_free(cwd_str); /* FIXME: This cannot cover 100% cases since symlinks are not checked. * There may be other cases that cwd is actually under mount root * but checking prefix is not enough. We already did our best, though. */ if(g_file_has_prefix(cwd, root)) g_chdir("/"); g_object_unref(cwd); g_object_unref(root); }
SeedValue ghtml_webview_js_chdir (SeedContext ctx, SeedObject function, SeedObject thisObject, size_t argumentCount, SeedValue arguments[], SeedException * exception) { if (argumentCount != 1) { seed_make_exception (ctx, exception, GHTML_JS_INVALID_PARAMS, "chdir expected 1 argument, got %zd", argumentCount ); return seed_make_null (ctx); } gchar * val = seed_value_to_string(ctx, arguments[0], exception); SeedValue result = (SeedValue) JSValueMakeNumber(ctx, g_chdir(val)); g_free(val); return result; }
void destroy_testbed(char *path) { char *command = g_strdup_printf("rm -rf %s", path); if (olddir) { if (g_chdir(olddir) < 0) abort(); g_free(olddir); } if (osync_system(command)) abort(); g_free(command); osync_trace(TRACE_INTERNAL, "Tearing down %s", path); g_free(path); }
void menuOpenData(GtkMenuItem* item, gpointer data) { GtkWidget* d; gchar* path = NULL; FILE* f; gchar* err = NULL; gchar* title; geoData = NULL; d = gtk_file_chooser_dialog_new("Open Data", GTK_WINDOW(data), GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL, GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT, NULL); if (gtk_dialog_run(GTK_DIALOG(d)) == GTK_RESPONSE_ACCEPT) { path = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(d)); } gtk_widget_destroy(d); if (path == NULL) { return; } g_chdir(path); g_free(path); f = fopen("records.csv", "r"); geoData = BioGeoRead(f, &err); fclose(f); if (err != NULL) { errMsg(GTK_WINDOW(data), err); g_free(err); return; } f = fopen("trees.csv", "r"); treeData = TreeRead(f, &err); fclose(f); if (err != NULL) { errMsg(GTK_WINDOW(data), err); g_free(err); return; } PrepareTrees(treeData, geoData); changeTree(g_ptr_array_index(treeData, 0)); gtk_widget_set_sensitive(GTK_WIDGET(item), FALSE); gtk_widget_set_sensitive(itemRecons, TRUE); title = g_strdup_printf("ev.view: %s", activeTree->ID); gtk_window_set_title(GTK_WINDOW(data), title); g_free(title); }
gchar * thunar_util_change_working_directory (const gchar *new_directory) { gchar *old_directory; _thunar_return_val_if_fail (new_directory != NULL && *new_directory != '\0', NULL); /* try to determine the current working directory */ old_directory = g_get_current_dir(); /* try switching to the new working directory */ if (g_chdir (new_directory) != 0) { /* switching failed, we don't need to return the old directory */ g_free (old_directory); old_directory = NULL; } return old_directory; }
int main(int argc, char** argv) { GError *err = NULL; GMappedFile *map; char *buf = NULL, *pbuf = NULL, *data = NULL, *end; gsize len = 0; char *extract_path; gtk_init( &argc, &argv ); /* load the executable file itself */ map = g_mapped_file_new( argv[0], FALSE, NULL ); if( !map ) return 1; buf = g_mapped_file_get_contents(map); len = g_mapped_file_get_length( map ); /* find the data */ magic[0] = '_'; for( pbuf = buf, end = buf + len - magic_len; G_LIKELY( pbuf < end ); ++pbuf ) { if( G_UNLIKELY( 0 == memcmp( pbuf, magic, magic_len ) ) ) { data = pbuf + magic_len + 1; break; } } if( G_UNLIKELY( ! data ) ) { g_mapped_file_free( map ); show_error( "檔案損毀,請重新下載。" ); return 1; /* error! no data found */ } len -= (data - buf); /* skip ourself */ extract_path = g_strconcat( "/tmp/Lazyscripts-", g_get_user_name(), NULL ); g_mkdir_with_parents( extract_path, 0755 ); /* FIXME: is 0755 OK? */ cmdv[3] = extract_path; if( g_spawn_async_with_pipes( NULL, cmdv, NULL, G_SPAWN_SEARCH_PATH|G_SPAWN_DO_NOT_REAP_CHILD, NULL, NULL, &pid, &std_in, NULL, NULL, &err ) ) { int status = 0; write( std_in, data, len ); close( std_in ); waitpid( pid, &status, 0 ); g_spawn_close_pid( pid ); } else { show_error( err->message ); g_error_free( err ); } g_mapped_file_free( map ); g_chdir( extract_path ); g_free( extract_path ); g_chdir( "Lazyscripts" ); execl( "slzs gui", NULL ); show_error("錯誤,無法執行 Lazybuntu!"); return 0; }
static gint pacman_transfer_with_command (PacmanManager *manager, const gchar *url, const gchar *path, gboolean again, gpointer user_data) { const gchar *transfer_command = (const gchar *) user_data; GRegex *input, *output; gchar *old_pwd, *basename, *tempname, *filename; gchar *temp_command, *final_command; gint status = -1; g_return_val_if_fail (url != NULL, FALSE); g_return_val_if_fail (path != NULL, FALSE); g_return_val_if_fail (transfer_command != NULL, FALSE); old_pwd = g_get_current_dir (); if (g_chdir (path) < 0) { g_warning ("Could not locate download directory %s\n", path); g_free (old_pwd); return status; } input = g_regex_new ("%u", 0, 0, NULL); if (input == NULL) { g_chdir (old_pwd); g_free (old_pwd); return status; } output = g_regex_new ("%o", 0, 0, NULL); if (output == NULL) { g_regex_unref (input); g_chdir (old_pwd); g_free (old_pwd); return status; } basename = g_path_get_basename (url); tempname = g_strdup_printf ("%s%s.part", path, basename); filename = g_strdup_printf ("%s%s", path, basename); if (again && g_file_test (tempname, G_FILE_TEST_EXISTS)) { g_unlink (tempname); } if (again && g_file_test (filename, G_FILE_TEST_EXISTS)) { g_unlink (filename); } temp_command = g_regex_replace_literal (output, transfer_command, -1, 0, tempname, 0, NULL); if (temp_command != NULL) { if (strcmp (temp_command, transfer_command) == 0) { /* not using .part filename */ g_free (tempname); tempname = NULL; } final_command = g_regex_replace_literal (input, temp_command, -1, 0, url, 0, NULL); if (final_command != NULL) { if (!g_spawn_command_line_sync (final_command, NULL, NULL, &status, NULL)) { g_warning ("Could not run transfer command %s\n", final_command); status = -1; } else if (WIFEXITED (status) == 0) { g_warning ("Transfer command did not terminate correctly\n"); status = -1; } else if (WEXITSTATUS (status) != EXIT_SUCCESS) { g_warning ("Transfer command returned error code %d\n", WEXITSTATUS (status)); status = -1; } else { status = 0; if (tempname != NULL) { /* using .part filename */ if (g_rename (tempname, filename) < 0) { g_warning ("Could not rename resulting file %s\n", tempname); status = -1; } } } } } if (final_command != NULL) { g_free (final_command); g_free (temp_command); } g_free (filename); g_free (basename); g_free (tempname); g_regex_unref (output); g_regex_unref (input); g_chdir (old_pwd); g_free (old_pwd); return status; }
void SludgeProjectManager::readIniFile() { if (g_chdir(g_get_user_config_dir())) return; #ifdef __WIN32 _mkdir("sludge-devkit"); #else g_mkdir("sludge-devkit", 0000777); #endif g_chdir("sludge-devkit"); FILE * fp = fopen("SLUDGE.ini", "rb"); programSettings.compilerKillImages = 0; programSettings.compilerWriteStrings = 0; programSettings.compilerVerbose = 1; programSettings.searchSensitive = 0; #ifdef __WIN32 sprintf(editor, "%s", "notepad.exe"); sprintf(imageViewer, "%s", "rundll32.exe shimgvw.dll,ImageView_Fullscreen"); sprintf(audioPlayer, "%s", "mplay32.exe"); sprintf(modPlayer, "%s", ""); #else sprintf(editor, "%s", "gedit"); sprintf(imageViewer, "%s", "eog"); sprintf(audioPlayer, "%s", "totem"); sprintf(modPlayer, "%s", "totem"); #endif if (fp) { char lineSoFar[257] = ""; char secondSoFar[257] = ""; unsigned char here = 0; char readChar = ' '; bool keepGoing = true; bool doingSecond = false; do { readChar = fgetc(fp); if (feof(fp)) { readChar = '\x0D'; keepGoing = false; } switch (readChar) { case '\x0D': case '\x0A': if (!keepGoing) { fprintf(fp, "KillImages=%d\x0D\x0A", programSettings.compilerKillImages); fprintf(fp, "WriteStrings=%d\x0D\x0A", programSettings.compilerWriteStrings); fprintf(fp, "Verbose=%d\x0D\x0A", programSettings.compilerVerbose); fprintf(fp, "SearchSensitive=%d\x0D\x0A", programSettings.searchSensitive); fprintf(fp, "Editor=%s\x0D\x0A", editor); fprintf(fp, "ImageViewer=%s\x0D\x0A", imageViewer); fprintf(fp, "AudioPlayer=%s\x0D\x0A", audioPlayer); fprintf(fp, "ModPlayer=%s\x0D\x0A", modPlayer); } if (doingSecond) { if (strcmp(lineSoFar, "KillImages") == 0) { programSettings.compilerKillImages = atoi(secondSoFar); } else if (strcmp(lineSoFar, "WriteStrings") == 0) { programSettings.compilerWriteStrings = atoi(secondSoFar); } else if (strcmp(lineSoFar, "Verbose") == 0) { programSettings.compilerVerbose = atoi(secondSoFar); } else if (strcmp(lineSoFar, "SearchSensitive") == 0) { programSettings.searchSensitive = atoi(secondSoFar); } else if (strcmp(lineSoFar, "Editor") == 0) { sprintf(editor, "%s", secondSoFar); } else if (strcmp(lineSoFar, "ImageViewer") == 0) { sprintf(imageViewer, "%s", secondSoFar); } else if (strcmp(lineSoFar, "AudioPlayer") == 0) { sprintf(audioPlayer, "%s", secondSoFar); } else if (strcmp(lineSoFar, "ModPlayer") == 0) { sprintf(modPlayer, "%s", secondSoFar); } } here = 0; doingSecond = false; lineSoFar[0] = 0; secondSoFar[0] = 0; break; case '=': doingSecond = true; here = 0; break; default: if (doingSecond) { secondSoFar[here ++] = readChar; secondSoFar[here] = 0; } else { lineSoFar[here ++] = readChar; lineSoFar[here] = 0; } break; } } while (keepGoing); fclose(fp); } g_chdir(workingDir); }
static void cmd_export_impl (void *data, int argc, char **argv) { int i; GError *err = NULL; gchar *tmp; const gchar *out_suffix; struct ExportFormat *exporter = NULL; GArray *render_color_map = NULL; gchar *original_cwd = g_get_current_dir (); gtk_init_check (&argc, &argv); scm_init_guile (); libgeda_init (); scm_dynwind_begin (0); toplevel = s_toplevel_new (); edascm_dynwind_toplevel (toplevel); /* Now load rc files, if necessary */ if (getenv ("GAF_INHIBIT_RCFILES") == NULL) { g_rc_parse (toplevel, "gaf export", NULL, NULL); } i_vars_libgeda_set (toplevel); /* Ugh */ /* Parse configuration files */ export_config (); /* Parse command-line arguments */ export_command_line (argc, argv); /* If no format was specified, try and guess from output * filename. */ if (settings.format == NULL) { out_suffix = strrchr (settings.outfile, '.'); if (out_suffix != NULL) { out_suffix++; /* Skip '.' */ } else { fprintf (stderr, _("ERROR: Cannot infer output format from filename '%s'.\n"), settings.outfile); exit (1); } } /* Try and find an exporter function */ tmp = g_utf8_strdown ((settings.format == NULL) ? out_suffix : settings.format, -1); for (i = 0; formats[i].name != NULL; i++) { if (strcmp (tmp, formats[i].alias) == 0) { exporter = &formats[i]; break; } } if (exporter == NULL) { if (settings.format == NULL) { fprintf (stderr, _("ERROR: Cannot find supported format for filename '%s'.\n"), settings.outfile); exit (1); } else { fprintf (stderr, _("ERROR: Unsupported output format '%s'.\n"), settings.format); fprintf (stderr, see_help_msg); exit (1); } } g_free (tmp); /* If more than one schematic/symbol file was specified, check that * exporter supports multipage output. */ if ((settings.infilec > 1) && !(exporter->flags & OUTPUT_MULTIPAGE)) { fprintf (stderr, _("ERROR: Selected output format does not support multipage output\n")); exit (1); } /* Load schematic files */ while (optind < argc) { PAGE *page; tmp = argv[optind++]; page = s_page_new (toplevel, tmp); if (!f_open (toplevel, page, tmp, &err)) { fprintf (stderr, _("ERROR: Failed to load '%s': %s\n"), tmp, err->message); exit (1); } if (g_chdir (original_cwd) != 0) { fprintf (stderr, _("ERROR: Failed to change directory to '%s': %s\n"), original_cwd, g_strerror (errno)); exit (1); } } /* Create renderer */ renderer = eda_renderer_new (NULL, NULL); if (settings.font != NULL) { g_object_set (renderer, "font-name", settings.font, NULL); } /* Make sure libgeda knows how to calculate the bounds of text * taking into account font etc. */ o_text_set_rendered_bounds_func (toplevel, export_text_rendered_bounds, renderer); /* Create color map */ render_color_map = g_array_sized_new (FALSE, FALSE, sizeof(GedaColor), MAX_COLORS); render_color_map = g_array_append_vals (render_color_map, print_colors, MAX_COLORS); if (!settings.color) { /* Create a black and white color map. All non-background colors * are black. */ GedaColor white = {~0, ~0, ~0, ~0, TRUE}; GedaColor black = {0, 0, 0, ~0, TRUE}; for (i = 0; i < MAX_COLORS; i++) { GedaColor *c = &g_array_index (render_color_map, GedaColor, i); if (!c->enabled) continue; if (c->a == 0) { c->enabled = FALSE; continue; } if (i == OUTPUT_BACKGROUND_COLOR) { *c = white; } else { *c = black; } } } eda_renderer_set_color_map (renderer, render_color_map); /* Render */ exporter->func (); scm_dynwind_end (); exit (0); }
G_MODULE_EXPORT void on_rename_perscomm_activate(GtkMenuItem *menuitem, gpointer user_data) { if (is_dialog) return; #if defined(WIN32) gui_generic_warning(_("Renaming is not available in Windows.\n\n" "Xiphos is limited by Windows' filesystem,\n" "because it disallows the renaming of filename\n" "components of currently-open files,\n" "such as the contents of this commentary.\n" "Therefore, personal commentary renaming is\n" "not available in the Windows environment.")); #else GS_DIALOG *info; GString *workstr; char *s; char *datapath_old, *datapath_new; const char *conf_old; char *conf_new; char *sworddir, *modsdir; FILE *result; // get a new name for the module. info = gui_new_dialog(); info->title = _("Rename Commentary"); workstr = g_string_new(""); g_string_printf(workstr, "<span weight=\"bold\">%s</span>", _("Choose Commentary Name")); info->label_top = workstr->str; info->text1 = g_strdup(_("New Name")); info->label1 = N_("Name: "); info->ok = TRUE; info->cancel = TRUE; if (gui_gs_dialog(info) != GS_OK) goto out1; for (s = info->text1; *s; ++s) { if (!isalnum(*s) && (*s != '_')) { gui_generic_warning_modal(_("Module names must contain [A-Za-z0-9_] only.")); goto out1; } } if (main_is_module(info->text1)) { gui_generic_warning_modal(_("Xiphos already knows a module by that name.")); goto out1; } sworddir = g_strdup_printf("%s/" DOTSWORD, settings.homedir); modsdir = g_strdup_printf("%s/mods.d", sworddir); conf_old = main_get_mod_config_file(settings.CommWindowModule, sworddir); conf_new = g_strdup(info->text1); // dirname is lowercase. for (s = conf_new; *s; ++s) if (isupper(*s)) *s = tolower(*s); datapath_old = main_get_mod_config_entry(settings.CommWindowModule, "DataPath"); datapath_new = g_strdup(datapath_old); if ((s = strstr(datapath_new, "rawfiles/")) == NULL) { gui_generic_warning_modal("Malformed datapath in old configuration!"); goto out2; } *(s + 9) = '\0'; // skip past "rawfiles/". s = g_strdup_printf("%s%s", datapath_new, conf_new); g_free(datapath_new); // out with the old... datapath_new = s; // ..and in with the new. // move old data directory to new. if ((g_chdir(sworddir) != 0) || (rename(datapath_old, datapath_new) != 0)) { gui_generic_warning_modal("Failed to rename directory."); goto out2; } // manufacture new .conf from old. g_string_printf(workstr, "( cd \"%s\" && sed -e '/^\\[/s|^.*$|[%s]|' -e '/^DataPath=/s|rawfiles/.*$|rawfiles/%s/|' < \"%s\" > \"%s.conf\" ) 2>&1", modsdir, info->text1, conf_new, conf_old, conf_new); if ((result = popen(workstr->str, "r")) == NULL) { g_string_printf(workstr, _("Failed to create new configuration:\n%s"), strerror(errno)); gui_generic_warning_modal(workstr->str); goto out2; } else { gchar output[258]; if (fgets(output, 256, result) != NULL) { g_string_truncate(workstr, 0); g_string_append(workstr, _("Configuration build error:\n\n")); g_string_append(workstr, output); gui_generic_warning_modal(workstr->str); goto out2; // necessary? advisable? } pclose(result); } // unlink old conf. g_string_printf(workstr, "%s/%s", modsdir, conf_old); if (unlink(workstr->str) != 0) { g_string_printf(workstr, "Unlink of old configuration failed:\n%s", strerror(errno)); gui_generic_warning_modal(workstr->str); goto out2; } main_update_module_lists(); settings.CommWindowModule = g_strdup(info->text1); main_display_commentary(info->text1, settings.currentverse); out2: g_free(conf_new); g_free((char *)conf_old); g_free(datapath_old); g_free(datapath_new); g_free(modsdir); g_free(sworddir); out1: g_free(info->text1); g_free(info); g_string_free(workstr, TRUE); #endif /* !WIN32 */ }
static int run_bridge (const gchar *interactive, gboolean privileged_slave) { CockpitTransport *transport; gboolean terminated = FALSE; gboolean interupted = FALSE; gboolean closed = FALSE; CockpitPortal *super = NULL; CockpitPortal *pcp = NULL; gpointer polkit_agent = NULL; const gchar *directory; struct passwd *pwd; GPid daemon_pid = 0; GPid agent_pid = 0; guint sig_term; guint sig_int; int outfd; uid_t uid; cockpit_set_journal_logging (G_LOG_DOMAIN, !isatty (2)); /* * The bridge always runs from within $XDG_RUNTIME_DIR * This makes it easy to create user sockets and/or files. */ if (!privileged_slave) { directory = g_get_user_runtime_dir (); if (g_mkdir_with_parents (directory, 0700) < 0) g_warning ("couldn't create runtime dir: %s: %s", directory, g_strerror (errno)); else if (g_chdir (directory) < 0) g_warning ("couldn't change to runtime dir: %s: %s", directory, g_strerror (errno)); } /* Always set environment variables early */ uid = geteuid(); pwd = getpwuid_a (uid); if (pwd == NULL) { g_message ("couldn't get user info: %s", g_strerror (errno)); } else { g_setenv ("USER", pwd->pw_name, TRUE); g_setenv ("HOME", pwd->pw_dir, TRUE); g_setenv ("SHELL", pwd->pw_shell, TRUE); } /* Reset the umask, typically this is done in .bashrc for a login shell */ umask (022); /* * This process talks on stdin/stdout. However lots of stuff wants to write * to stdout, such as g_debug, and uses fd 1 to do that. Reroute fd 1 so that * it goes to stderr, and use another fd for stdout. */ outfd = dup (1); if (outfd < 0 || dup2 (2, 1) < 1) { g_warning ("bridge couldn't redirect stdout to stderr"); outfd = 1; } sig_term = g_unix_signal_add (SIGTERM, on_signal_done, &terminated); sig_int = g_unix_signal_add (SIGINT, on_signal_done, &interupted); g_type_init (); /* Start daemons if necessary */ if (!interactive && !privileged_slave) { if (!have_env ("DBUS_SESSION_BUS_ADDRESS")) daemon_pid = start_dbus_daemon (); if (!have_env ("SSH_AUTH_SOCK")) agent_pid = start_ssh_agent (); } packages = cockpit_packages_new (); cockpit_dbus_internal_startup (interactive != NULL); if (interactive) { /* Allow skipping the init message when interactive */ init_received = TRUE; transport = cockpit_interact_transport_new (0, outfd, interactive); } else { transport = cockpit_pipe_transport_new_fds ("stdio", 0, outfd); } if (uid != 0) { if (!interactive) polkit_agent = cockpit_polkit_agent_register (transport, NULL); super = cockpit_portal_new_superuser (transport); } g_resources_register (cockpitassets_get_resource ()); cockpit_web_failure_resource = "/org/cockpit-project/Cockpit/fail.html"; pcp = cockpit_portal_new_pcp (transport); cockpit_dbus_time_startup (); cockpit_dbus_user_startup (pwd); cockpit_dbus_setup_startup (); g_free (pwd); pwd = NULL; g_signal_connect (transport, "control", G_CALLBACK (on_transport_control), NULL); g_signal_connect (transport, "closed", G_CALLBACK (on_closed_set_flag), &closed); send_init_command (transport); /* Owns the channels */ channels = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_object_unref); while (!terminated && !closed && !interupted) g_main_context_iteration (NULL, TRUE); if (polkit_agent) cockpit_polkit_agent_unregister (polkit_agent); if (super) g_object_unref (super); g_object_unref (pcp); g_object_unref (transport); g_hash_table_destroy (channels); cockpit_dbus_internal_cleanup (); cockpit_packages_free (packages); packages = NULL; if (daemon_pid) kill (daemon_pid, SIGTERM); if (agent_pid) kill (agent_pid, SIGTERM); g_source_remove (sig_term); g_source_remove (sig_int); /* So the caller gets the right signal */ if (terminated) raise (SIGTERM); return 0; }
int main(int argc, char **argv) { /* These are relative to top_builddir */ const char * const path_directories[] = { GJS_TOP_SRCDIR"/modules", GJS_TOP_SRCDIR"/test/js/modules", ".libs:", NULL }; char *js_test_dir; char *working_dir; char *gjs_unit_path; char *gjs_unit_dir; char *top_builddir; char *data_home; const char *name; GString *path; GDir *dir; size_t i; working_dir = g_get_current_dir(); if(g_path_is_absolute(argv[0])) gjs_unit_path = g_strdup(argv[0]); else gjs_unit_path = g_build_filename(working_dir, argv[0], NULL); gjs_unit_dir = g_path_get_dirname(gjs_unit_path); /* the gjs-unit executable will be in <top_builddir>/.libs */ top_builddir = g_build_filename(gjs_unit_dir, "..", NULL); top_srcdir = g_build_filename(top_builddir, GJS_TOP_SRCDIR, NULL); /* Normalize, not strictly necessary */ g_chdir(top_builddir); g_free(top_builddir); top_builddir = g_get_current_dir(); g_chdir(top_srcdir); g_free(top_srcdir); top_srcdir = g_get_current_dir(); g_chdir(working_dir); /* we're always going to use uninstalled files, set up necessary * environment variables, but don't overwrite if already set */ data_home = g_build_filename(top_builddir, "test_user_data", NULL); path = g_string_new(NULL); for(i = 0; i < G_N_ELEMENTS(path_directories); i++) { char *directory; if (i != 0) g_string_append_c(path, ':'); directory = g_build_filename(top_builddir, path_directories[i], NULL); g_string_append(path, directory); g_free(directory); } g_setenv("TOP_SRCDIR", top_srcdir, FALSE); g_setenv("BUILDDIR", top_builddir, FALSE); g_setenv("XDG_DATA_HOME", data_home, FALSE); g_setenv("GJS_PATH", path->str, FALSE); gjs_crash_after_timeout(60*7); /* give the unit tests 7 minutes to complete */ gjs_init_sleep_on_crash(); setlocale(LC_ALL, ""); g_test_init(&argc, &argv, NULL); g_type_init(); /* iterate through all 'test*.js' files in ${top_srcdir}/test/js */ js_test_dir = g_build_filename(top_srcdir, "test", "js", NULL); dir = g_dir_open(js_test_dir, 0, NULL); g_assert(dir != NULL); while ((name = g_dir_read_name(dir)) != NULL) { char *test_name; char *file_name; if (!(g_str_has_prefix(name, "test") && g_str_has_suffix(name, ".js"))) continue; /* pretty print, drop 'test' prefix and '.js' suffix from test name */ test_name = g_strconcat("/js/", name + 4, NULL); test_name[strlen(test_name)-3] = '\0'; file_name = g_build_filename(js_test_dir, name, NULL); g_test_add(test_name, GjsTestJSFixture, file_name, setup, test, teardown); g_free(test_name); /* not freeing file_name as it's needed while running the test */ } g_dir_close(dir); return g_test_run (); }
int main (int argc, char *argv[]) { GOptionContext *context; GError *error = NULL; #ifdef G_OS_WIN32 if (fileno (stdout) != -1 && _get_osfhandle (fileno (stdout)) != -1) { /* stdout is fine, presumably redirected to a file or pipe */ } else { typedef BOOL (* WINAPI AttachConsole_t) (DWORD); AttachConsole_t p_AttachConsole = (AttachConsole_t) GetProcAddress (GetModuleHandle ("kernel32.dll"), "AttachConsole"); if (p_AttachConsole != NULL && p_AttachConsole (ATTACH_PARENT_PROCESS)) { freopen ("CONOUT$", "w", stdout); dup2 (fileno (stdout), 1); freopen ("CONOUT$", "w", stderr); dup2 (fileno (stderr), 2); } } #endif #if (!GLIB_CHECK_VERSION(2,31,0)) /* Remove this once we bump dependencies to glib >= 2.31.0 */ /* Init glib threads asap */ if (!g_thread_supported ()) g_thread_init (NULL); #endif #ifdef ENABLE_NLS /* Initialize the i18n stuff */ bindtextdomain (GETTEXT_PACKAGE, ev_get_locale_dir()); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); #endif context = g_option_context_new (N_("GNOME Document Viewer")); g_option_context_set_translation_domain(context, GETTEXT_PACKAGE); g_option_context_add_main_entries (context, goption_options, GETTEXT_PACKAGE); #ifdef WITH_SMCLIENT g_option_context_add_group (context, egg_sm_client_get_option_group ()); #endif g_option_context_add_group (context, gtk_get_option_group (TRUE)); if (!g_option_context_parse (context, &argc, &argv, &error)) { g_printerr ("Cannot parse arguments: %s\n", error->message); g_error_free (error); g_option_context_free (context); return 1; } g_option_context_free (context); if (preview_mode) { gboolean retval; retval = launch_previewer (); return retval ? 0 : 1; } if (!ev_init ()) return 1; ev_stock_icons_init (); #if defined(WITH_SMCLIENT) && defined(GDK_WINDOWING_X11) egg_set_desktop_file (GNOMEDATADIR "/applications/evince.desktop"); #else /* Manually set name and icon */ g_set_application_name (_("Document Viewer")); gtk_window_set_default_icon_name ("evince"); #endif /* WITH_SMCLIENT && GDK_WINDOWING_X11 */ ev_application_load_session (EV_APP); load_files (file_arguments); /* Change directory so we don't prevent unmounting in case the initial cwd * is on an external device (see bug #575436) */ g_chdir (g_get_home_dir ()); gtk_main (); ev_shutdown (); ev_stock_icons_shutdown (); return 0; }
/** * Function to open and perform a optimization. */ void optimize_open () { GTimeZone *tz; GDateTime *t0, *t; unsigned int i, j; #if DEBUG_OPTIMIZE char *buffer; fprintf (stderr, "optimize_open: start\n"); #endif // Getting initial time #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: getting initial time\n"); #endif tz = g_time_zone_new_utc (); t0 = g_date_time_new_now (tz); // Obtaining and initing the pseudo-random numbers generator seed #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: getting initial seed\n"); #endif if (optimize->seed == DEFAULT_RANDOM_SEED) optimize->seed = input->seed; gsl_rng_set (optimize->rng, optimize->seed); // Replacing the working directory #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: replacing the working directory\n"); #endif g_chdir (input->directory); // Getting results file names optimize->result = input->result; optimize->variables = input->variables; // Obtaining the simulator file optimize->simulator = input->simulator; // Obtaining the evaluator file optimize->evaluator = input->evaluator; // Reading the algorithm optimize->algorithm = input->algorithm; switch (optimize->algorithm) { case ALGORITHM_MONTE_CARLO: optimize_algorithm = optimize_MonteCarlo; break; case ALGORITHM_SWEEP: optimize_algorithm = optimize_sweep; break; case ALGORITHM_ORTHOGONAL: optimize_algorithm = optimize_orthogonal; break; default: optimize_algorithm = optimize_genetic; optimize->mutation_ratio = input->mutation_ratio; optimize->reproduction_ratio = input->reproduction_ratio; optimize->adaptation_ratio = input->adaptation_ratio; } optimize->nvariables = input->nvariables; optimize->nsimulations = input->nsimulations; optimize->niterations = input->niterations; optimize->nbest = input->nbest; optimize->tolerance = input->tolerance; optimize->nsteps = input->nsteps; optimize->nestimates = 0; optimize->threshold = input->threshold; optimize->stop = 0; if (input->nsteps) { optimize->relaxation = input->relaxation; switch (input->climbing) { case CLIMBING_METHOD_COORDINATES: optimize->nestimates = 2 * optimize->nvariables; optimize_estimate_climbing = optimize_estimate_climbing_coordinates; break; default: optimize->nestimates = input->nestimates; optimize_estimate_climbing = optimize_estimate_climbing_random; } } #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nbest=%u\n", optimize->nbest); #endif optimize->simulation_best = (unsigned int *) alloca (optimize->nbest * sizeof (unsigned int)); optimize->error_best = (double *) alloca (optimize->nbest * sizeof (double)); // Reading the experimental data #if DEBUG_OPTIMIZE buffer = g_get_current_dir (); fprintf (stderr, "optimize_open: current directory=%s\n", buffer); g_free (buffer); #endif optimize->nexperiments = input->nexperiments; optimize->ninputs = input->experiment->ninputs; optimize->experiment = (char **) alloca (input->nexperiments * sizeof (char *)); optimize->weight = (double *) alloca (input->nexperiments * sizeof (double)); for (i = 0; i < input->experiment->ninputs; ++i) optimize->file[i] = (GMappedFile **) g_malloc (input->nexperiments * sizeof (GMappedFile *)); for (i = 0; i < input->nexperiments; ++i) { #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: i=%u\n", i); #endif optimize->experiment[i] = input->experiment[i].name; optimize->weight[i] = input->experiment[i].weight; #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: experiment=%s weight=%lg\n", optimize->experiment[i], optimize->weight[i]); #endif for (j = 0; j < input->experiment->ninputs; ++j) { #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: stencil%u\n", j + 1); #endif optimize->file[j][i] = g_mapped_file_new (input->experiment[i].stencil[j], 0, NULL); } } // Reading the variables data #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: reading variables\n"); #endif optimize->label = (char **) alloca (input->nvariables * sizeof (char *)); j = input->nvariables * sizeof (double); optimize->rangemin = (double *) alloca (j); optimize->rangeminabs = (double *) alloca (j); optimize->rangemax = (double *) alloca (j); optimize->rangemaxabs = (double *) alloca (j); optimize->step = (double *) alloca (j); j = input->nvariables * sizeof (unsigned int); optimize->precision = (unsigned int *) alloca (j); optimize->nsweeps = (unsigned int *) alloca (j); optimize->nbits = (unsigned int *) alloca (j); for (i = 0; i < input->nvariables; ++i) { optimize->label[i] = input->variable[i].name; optimize->rangemin[i] = input->variable[i].rangemin; optimize->rangeminabs[i] = input->variable[i].rangeminabs; optimize->rangemax[i] = input->variable[i].rangemax; optimize->rangemaxabs[i] = input->variable[i].rangemaxabs; optimize->precision[i] = input->variable[i].precision; optimize->step[i] = input->variable[i].step; optimize->nsweeps[i] = input->variable[i].nsweeps; optimize->nbits[i] = input->variable[i].nbits; } if (input->algorithm == ALGORITHM_SWEEP || input->algorithm == ALGORITHM_ORTHOGONAL) { optimize->nsimulations = 1; for (i = 0; i < input->nvariables; ++i) { optimize->nsimulations *= optimize->nsweeps[i]; #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nsweeps=%u nsimulations=%u\n", optimize->nsweeps[i], optimize->nsimulations); #endif } } if (optimize->nsteps) optimize->climbing = (double *) alloca (optimize->nvariables * sizeof (double)); // Setting error norm switch (input->norm) { case ERROR_NORM_EUCLIDIAN: optimize_norm = optimize_norm_euclidian; break; case ERROR_NORM_MAXIMUM: optimize_norm = optimize_norm_maximum; break; case ERROR_NORM_P: optimize_norm = optimize_norm_p; optimize->p = input->p; break; default: optimize_norm = optimize_norm_taxicab; } // Allocating values #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: allocating variables\n"); fprintf (stderr, "optimize_open: nvariables=%u algorithm=%u\n", optimize->nvariables, optimize->algorithm); #endif optimize->genetic_variable = NULL; if (optimize->algorithm == ALGORITHM_GENETIC) { optimize->genetic_variable = (GeneticVariable *) g_malloc (optimize->nvariables * sizeof (GeneticVariable)); for (i = 0; i < optimize->nvariables; ++i) { #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: i=%u min=%lg max=%lg nbits=%u\n", i, optimize->rangemin[i], optimize->rangemax[i], optimize->nbits[i]); #endif optimize->genetic_variable[i].minimum = optimize->rangemin[i]; optimize->genetic_variable[i].maximum = optimize->rangemax[i]; optimize->genetic_variable[i].nbits = optimize->nbits[i]; } } #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nvariables=%u nsimulations=%u\n", optimize->nvariables, optimize->nsimulations); #endif optimize->value = (double *) g_malloc ((optimize->nsimulations + optimize->nestimates * optimize->nsteps) * optimize->nvariables * sizeof (double)); // Calculating simulations to perform for each task #if HAVE_MPI #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: rank=%u ntasks=%u\n", optimize->mpi_rank, ntasks); #endif optimize->nstart = optimize->mpi_rank * optimize->nsimulations / ntasks; optimize->nend = (1 + optimize->mpi_rank) * optimize->nsimulations / ntasks; if (optimize->nsteps) { optimize->nstart_climbing = optimize->mpi_rank * optimize->nestimates / ntasks; optimize->nend_climbing = (1 + optimize->mpi_rank) * optimize->nestimates / ntasks; } #else optimize->nstart = 0; optimize->nend = optimize->nsimulations; if (optimize->nsteps) { optimize->nstart_climbing = 0; optimize->nend_climbing = optimize->nestimates; } #endif #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: nstart=%u nend=%u\n", optimize->nstart, optimize->nend); #endif // Calculating simulations to perform for each thread optimize->thread = (unsigned int *) alloca ((1 + nthreads) * sizeof (unsigned int)); for (i = 0; i <= nthreads; ++i) { optimize->thread[i] = optimize->nstart + i * (optimize->nend - optimize->nstart) / nthreads; #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: i=%u thread=%u\n", i, optimize->thread[i]); #endif } if (optimize->nsteps) optimize->thread_climbing = (unsigned int *) alloca ((1 + nthreads_climbing) * sizeof (unsigned int)); // Opening result files optimize->file_result = g_fopen (optimize->result, "w"); optimize->file_variables = g_fopen (optimize->variables, "w"); // Performing the algorithm switch (optimize->algorithm) { // Genetic algorithm case ALGORITHM_GENETIC: optimize_genetic (); break; // Iterative algorithm default: optimize_iterate (); } // Getting calculation time t = g_date_time_new_now (tz); optimize->calculation_time = 0.000001 * g_date_time_difference (t, t0); g_date_time_unref (t); g_date_time_unref (t0); g_time_zone_unref (tz); printf ("%s = %.6lg s\n", _("Calculation time"), optimize->calculation_time); fprintf (optimize->file_result, "%s = %.6lg s\n", _("Calculation time"), optimize->calculation_time); // Closing result files fclose (optimize->file_variables); fclose (optimize->file_result); #if DEBUG_OPTIMIZE fprintf (stderr, "optimize_open: end\n"); #endif }
char *setup_testbed(const char *fkt_name) { #ifndef _WIN32 setuid(65534); #endif char *testbed = g_strdup_printf("%s/testbed.XXXXXX", g_get_tmp_dir()); char *command = NULL, *dirname = NULL; #ifdef _WIN32 if(g_file_test(testbed, G_FILE_TEST_IS_DIR)) destroy_testbed(g_strdup(testbed)); if(g_mkdir(testbed,0777) < 0){ osync_trace(TRACE_INTERNAL, "%s: Cannot create testbed directory %s", __func__, testbed); abort(); } #else /* WIN32 */ if (!mkdtemp(testbed)) abort(); #endif /* WIN32 */ if (fkt_name) { dirname = g_strdup_printf(OPENSYNC_TESTDATA"/%s", fkt_name); if (!g_file_test(dirname, G_FILE_TEST_IS_DIR)) { osync_trace(TRACE_INTERNAL, "%s: Path %s not exist.", __func__, dirname); abort(); } command = g_strdup_printf("cp -R %s/* %s", dirname, testbed); if (osync_system(command)) abort(); g_free(command); /* special handling for the git repo, since git does not * support empty directories, check for a file named * "empty_dirs" and create every subdirectory listed * there that does not begin with a slash (relative dirs only) */ { char *empty_name = NULL; FILE *fh = NULL; empty_name = g_strdup_printf("%s/empty_dirs", dirname); if ((fh = fopen(empty_name, "r"))) { char line[100], *s; while ((s = fgets(line, sizeof(line), fh))) { int len = strlen(s); /* trim newline */ if (len && s[len-1] == '\n') s[len-1] = 0; /* only create relative paths */ if (len && s[0] != '/' && s[0] != '\\' && s[0] != '#') { char *newdir = g_strdup_printf("%s/%s", testbed, s); if (newdir) { g_mkdir_with_parents(newdir, 0755); g_free(newdir); } } } fclose(fh); } g_free(empty_name); } g_free(dirname); } dirname = g_strdup_printf("%s/formats", testbed); if (!g_file_test(dirname, G_FILE_TEST_IS_DIR)) { if (g_mkdir(dirname,0777) < 0) { osync_trace(TRACE_ERROR, "Could not create format direcotry %s", dirname); abort(); } } g_free(dirname); dirname = g_strdup_printf("%s/plugins", testbed); if (!g_file_test(dirname, G_FILE_TEST_IS_DIR)) { if (g_mkdir(dirname,0777) < 0) { osync_trace(TRACE_ERROR, "Could not create plugin direcotry %s", dirname); abort(); } } g_free(dirname); command = g_strdup_printf("cp ./mock-plugin/mock-sync.%s %s/plugins", G_MODULE_SUFFIX, testbed); if (osync_system(command)) abort(); g_free(command); command = g_strdup_printf("cp ./mock-plugin/mock-format.%s %s/formats", G_MODULE_SUFFIX, testbed); if (osync_system(command)) abort(); g_free(command); command = g_strdup_printf("cp -R %s/../../misc/schemas/*.xsd %s", OPENSYNC_TESTDATA, testbed); if (osync_system(command)) abort(); g_free(command); #ifndef _WIN32 /* chmod is useless on windows system */ command = g_strdup_printf("chmod -R 700 %s", testbed); if (osync_system(command)) abort(); g_free(command); #endif olddir = g_get_current_dir(); if (g_chdir(testbed) < 0){ osync_trace(TRACE_ERROR, "Could not chdir to testbed"); abort(); } reset_counters(); osync_trace(TRACE_INTERNAL, "Seting up %s at %s", fkt_name, testbed); /* printf("."); fflush(NULL);*/ reset_env(); return testbed; }
/* * _daemonize() * * The single fork method of becoming a daemon, causes the process * to become a session leader and process group leader. * * Params: * gd_pch_pid_filename -- pid filename * gd_b_force -- global to control overwrite of pid file * * Returns: * returns integer which is passed back to the parent process * values - EXIT_FAILURE Parent and 1st Child * - EXIT_ERROR AnyPid or error * - EXIT_SUCCESS Only the Daemon or GrandChild */ static gint _daemonize (gchar *pidfilename) { gint pidfile = 0; pid_t pid = 0; pid_t sid = 0; gint len = 0; gchar ch_buff[16]; g_return_val_if_fail(pidfilename != NULL, EXIT_ERROR); /* Fork off the parent process */ switch (pid = fork()) { case -1: /* error -- all out */ g_warning("Shutting down as Pid[%d]: fork(error=%s)", getpid(), strerror(errno)); return (EXIT_ERROR); break; case 0: /* new process */ sleep(1); break; default: /* Normal exit, pid equals child real pid */ return (EXIT_FAILURE); } /* Change the file mode mask */ umask(0); /* Change the current working directory */ if ((g_chdir("/")) < 0) { g_warning("Child[%d] is exiting: chdir(error=%s)", getpid(), strerror(errno)); exit(EXIT_ERROR); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { g_warning("Child[%d] is exiting: setsid(error=%s)", getpid(), strerror(errno)); exit(EXIT_ERROR); } pidfile = g_open(pidfilename, O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR |S_IWUSR|S_IRGRP|S_IROTH); if (pidfile == -1) { g_warning("Child Error: cannot open pidfile %s: %s", pidfilename, strerror(errno)); return (EXIT_ERROR); } len = snprintf(ch_buff, sizeof(ch_buff), "%d", getpid()); write(pidfile, ch_buff, len); if (close(pidfile) != 0) { g_error("Child Warning: cannot close pidfile %s: %s", pidfilename, strerror(errno)); } return (EXIT_SUCCESS); }
int main (int argc, char **argv) { GSThemeEngine *engine; GtkWidget *window; GError *error; gboolean ret; char *location = NULL; char *background_color = NULL; gboolean sort_images = FALSE; gboolean no_stretch = FALSE; GOptionEntry entries [] = { { "location", 0, 0, G_OPTION_ARG_STRING, &location, N_("Location to get images from"), N_("PATH") }, { "background-color", 0, 0, G_OPTION_ARG_STRING, &background_color, N_("Color to use for images background"), N_("\"#rrggbb\"") }, { "sort-images", 0, 0, G_OPTION_ARG_NONE, &sort_images, N_("Do not randomize pictures from location"), NULL }, { "no-stretch", 0, 0, G_OPTION_ARG_NONE, &no_stretch, N_("Do not try to stretch images on screen"), NULL }, { NULL } }; bindtextdomain (GETTEXT_PACKAGE, MATELOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); error = NULL; g_thread_init (NULL); ret = gtk_init_with_args (&argc, &argv, NULL, entries, NULL, &error); if (! ret) { g_message ("%s", error->message); g_error_free (error); exit (1); } g_chdir (g_get_home_dir ()); g_set_prgname ("slideshow"); window = gs_theme_window_new (); g_signal_connect (G_OBJECT (window), "delete-event", G_CALLBACK (gtk_main_quit), NULL); engine = g_object_new (GSTE_TYPE_SLIDESHOW, NULL); if (location == NULL) { location = xdg_user_dir_lookup ("PICTURES"); if (location == NULL || strcmp (location, "/tmp") == 0 || strcmp (location, g_get_home_dir ()) == 0) { free (location); location = g_build_filename (g_get_home_dir (), "Pictures", NULL); } } if (location != NULL) { g_object_set (engine, "images-location", location, NULL); } if (sort_images) { g_object_set (engine, "sort-images", sort_images, NULL); } if (background_color != NULL) { g_object_set (engine, "background-color", background_color, NULL); } if (no_stretch) { g_object_set (engine, "no-stretch", no_stretch, NULL); } gtk_container_add (GTK_CONTAINER (window), GTK_WIDGET (engine)); gtk_widget_show (GTK_WIDGET (engine)); gtk_window_set_default_size (GTK_WINDOW (window), 640, 480); gtk_widget_show (window); gtk_main (); return 0; }
gint main (gint argc, gchar **argv) { GtkApplication *application; GApplicationFlags flags; gchar *path; GError *error = NULL; bindtextdomain (GETTEXT_PACKAGE, LOCALEDIR); bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8"); textdomain (GETTEXT_PACKAGE); gtk_init_with_args ( &argc, &argv, NULL, entries, GETTEXT_PACKAGE, &error); if (error != NULL) g_error ("%s", error->message); /* This installs handlers for our custom debug log levels. */ gva_get_debug_flags (); /* Change the working directory to that of the MAME executable. * Why? Because SDLMAME's default configuration uses relative * search paths such as "rompath = roms". The paths are relative * to the directory containing the MAME executable, so we must run * from that directory in order for SDLMAME's default configuration * to work. Annoying, but a common problem for users. */ path = g_path_get_dirname (MAME_PROGRAM); g_chdir (path); g_free (path); if (opt_inspect != NULL) { gchar *value; value = gva_mame_get_config_value (opt_inspect, &error); if (value != NULL) { g_print ("%s\n", value); g_free (value); } else { g_printerr ("%s\n", error->message); g_clear_error (&error); } exit (EXIT_SUCCESS); } if (opt_version) { g_print ("%s\n", PACKAGE_STRING); exit (EXIT_SUCCESS); } if (opt_which_emulator) { g_print ("%s\n", MAME_PROGRAM); exit (EXIT_SUCCESS); } /* Register the application with the session bus. */ flags = G_APPLICATION_FLAGS_NONE; application = gtk_application_new (APPLICATION_ID, flags); g_application_register (G_APPLICATION (application), NULL, &error); if (error != NULL) g_error ("%s", error->message); /* If another instance is running, exit now. */ if (g_application_get_is_remote (G_APPLICATION (application))) { gint exit_status; if (opt_build_database) { g_printerr ( "Cannot build database: " PACKAGE_NAME " is already running\n"); exit_status = EXIT_FAILURE; } else { g_application_activate (G_APPLICATION (application)); exit_status = EXIT_SUCCESS; } g_object_unref (application); exit (exit_status); } else { GtkWindow *window; window = GTK_WINDOW (GVA_WIDGET_MAIN_WINDOW); gtk_application_add_window (application, window); } gtk_window_set_default_icon_name (PACKAGE); if (!gva_db_init (&error)) g_error ("%s", error->message); gva_main_init (); gva_play_back_init (); gva_preferences_init (); gva_properties_init (); gva_ui_init (); gva_categories_init (&error); gva_error_handle (&error); gva_history_init (&error); gva_error_handle (&error); gva_nplayers_init (&error); gva_error_handle (&error); g_idle_add (idle_start, NULL); g_idle_add (tweak_css, NULL); gtk_main (); g_object_unref (application); return EXIT_SUCCESS; }
static gint pk_alpm_fetchcb (const gchar *url, const gchar *path, gint force) { GRegex *xo, *xi; gint result = 0; g_autofree gchar *basename = NULL; g_autofree gchar *file = NULL; g_autofree gchar *finalcmd = NULL; g_autofree gchar *oldpwd = NULL; g_autofree gchar *part = NULL; g_autofree gchar *tempcmd = NULL; g_return_val_if_fail (url != NULL, -1); g_return_val_if_fail (path != NULL, -1); g_return_val_if_fail (xfercmd != NULL, -1); oldpwd = g_get_current_dir (); if (g_chdir (path) < 0) { g_warning ("could not find or read directory '%s'", path); g_free (oldpwd); return -1; } xo = g_regex_new ("%o", 0, 0, NULL); xi = g_regex_new ("%u", 0, 0, NULL); basename = g_path_get_basename (url); file = g_strconcat (path, basename, NULL); part = g_strconcat (file, ".part", NULL); if (force != 0 && g_file_test (part, G_FILE_TEST_EXISTS)) g_unlink (part); if (force != 0 && g_file_test (file, G_FILE_TEST_EXISTS)) g_unlink (file); tempcmd = g_regex_replace_literal (xo, xfercmd, -1, 0, part, 0, NULL); if (tempcmd == NULL) { result = -1; goto out; } finalcmd = g_regex_replace_literal (xi, tempcmd, -1, 0, url, 0, NULL); if (finalcmd == NULL) { result = -1; goto out; } if (!pk_alpm_spawn (finalcmd)) { result = -1; goto out; } if (g_strrstr (xfercmd, "%o") != NULL) { /* using .part filename */ if (g_rename (part, file) < 0) { g_warning ("could not rename %s", part); result = -1; goto out; } } out: g_regex_unref (xi); g_regex_unref (xo); g_chdir (oldpwd); return result; }