Need close GTK+ window after execute the function

Viewed 99

I am programming on linux program and I am trying to prepare program with GTK+3, but I don't know how close program automatically after execute the function without kill that execute.

the step that i want in my program is:

  1. open gtk window and this window there is button (open Xreader).
  2. press button, it tells system to execute xreader program.
  3. close gtk window automatically without needing to close xreader .

here is my code

#include<stdio.h>
#include<gtk/gtk.h>

static void 
open_app(GtkWidget *Widget, gpointer data){

system("xreader");
gtk_main_quit();

}
int main(int argc, char *argv[])
{
     GtkWidget *window;
     GtkWidget *button1;
     
  gtk_init(&argc, &argv);
/*make window */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  /*give name to the window*/
  gtk_window_set_title(GTK_WINDOW(window), "launcher");
  /*make size of window*/
  gtk_window_set_default_size(GTK_WINDOW(window), 700, 700);
  /*open the window in the meddal*/
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);

  button1 = gtk_button_new_with_label("Open Xreader");
  
  gtk_container_add(GTK_CONTAINER(window), button1);
  gtk_widget_show_all(window);

  g_signal_connect(button1,"clicked",G_CALLBACK(open_app), NULL);
  g_signal_connect(window, "destroy",
      G_CALLBACK(gtk_main_quit), NULL);

  gtk_main();

  return 0;
}

everytime trying to execute my program and press the button (open Xreader) gtk not close till close xreader .

1 Answers

You cannot use system here, because according to its documentation, https://man7.org/linux/man-pages/man3/system.3.html

system() returns after the command has been completed.

Since you are using gtk, don't forget library functions provided by glib. It has a bunch of functions related to process and thread handling. For example, you can use GSubprocess class from glib, g_subprocess_new.

#include <gtk/gtk.h>
#include <stdio.h>
#include <stdlib.h>
#include <glib.h>

static void open_app(GtkWidget *Widget, gpointer data) {
  g_subprocess_new(G_SUBPROCESS_FLAGS_NONE, NULL, "xreader", NULL);
  gtk_main_quit();
}

int main(int argc, char *argv[]) {
  GtkWidget *window;
  GtkWidget *button1;

  gtk_init(&argc, &argv);
  /*make window */
  window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  /*give name to the window*/
  gtk_window_set_title(GTK_WINDOW(window), "launcher");
  /*make size of window*/
  gtk_window_set_default_size(GTK_WINDOW(window), 700, 700);
  /*open the window in the meddal*/
  gtk_window_set_position(GTK_WINDOW(window), GTK_WIN_POS_CENTER);

  button1 = gtk_button_new_with_label("Open Xreader");

  gtk_container_add(GTK_CONTAINER(window), button1);
  gtk_widget_show_all(window);

  g_signal_connect(button1, "clicked", G_CALLBACK(open_app), NULL);
  g_signal_connect(window, "destroy", G_CALLBACK(gtk_main_quit), NULL);

  gtk_main();

  return 0;
}
Related