How to Launch "Application in Terminal" from (your) GTK Application
system(3)
executes an external command. This is an example that the external command is a CUI application.
int ret;
ret = system("/path/to/shellscript.sh");
If system(3)
is called from CUI application, standard output can be write to the terminal and standard input can be read from the terminal. But GTK+ applications (or any other typical GUI application) don't have the terminal.
For GTK+ application (without the terminal), the external command must be launch with terminal emulator.
Here is a simple example of launching /path/to/shellscript.sh
with terminal emulator.
int ret;
ret = system("xterm -e /path/to/shellscript.sh");
It's simple. But hard-coding "xterm -e "
is not smart.
Following example is depends on User's terminal emulator preference (e.g. Gnome Preferred Applications preference tool):
GAppInfo *appinfo = NULL;
gboolean ret = FALSE;
appinfo = g_app_info_create_from_commandline("/path/to/shellscript.sh",
NULL,
G_APP_INFO_CREATE_NEEDS_TERMINAL,
NULL);
g_assert(appinfo != NULL); // TODO error handling is not implemented.
ret = g_app_info_launch(appinfo, NULL, NULL, NULL);
g_assert(ret == TRUE); // TODO error handling is not implemented.
Note that:
- In this way, external application execute background. (
system(3)
function is foreground) - On my environment, following code does not work (segmentation fault at calling
g_app_info_create_from_commandline()
). GTK seems to be required.
#include <glib.h>
#include <gio/gio.h>
//#include <gtk/gtk.h>// !! HERE is required!
static const gchar *SCRIPT_PATH = "/path/to/shellscript.sh";
int main(int argc, char *argv[])
{
GAppInfo *appinfo = NULL;
gboolean ret = FALSE;
//gtk_init(&argc, &argv);// !! HERE is required!
appinfo = g_app_info_create_from_commandline(SCRIPT_PATH,
NULL,
G_APP_INFO_CREATE_NEEDS_TERMINAL,
NULL);
g_assert(appinfo != NULL); // TODO error handling is not implemented.
ret = g_app_info_launch(appinfo,
NULL,
NULL,
NULL);
g_assert(ret == TRUE); // TODO error handling is not implemented.
return 0;
}