Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@h4tr3d
Created March 23, 2016 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save h4tr3d/be98a871991e58fdacad to your computer and use it in GitHub Desktop.
Save h4tr3d/be98a871991e58fdacad to your computer and use it in GitHub Desktop.
Check that we run from terminal. If no: restart in the default terminal.
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <vector>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
void check_terminal(int argc, char **argv)
{
if (isatty(fileno(stdin)))
return;
// Run from GUI! Restart in terminal
auto pid = fork();
if (pid == 0) {
std::vector<char*> args;
args.reserve(argc + 2 + 1);
// Try to run default terminal emulator. Fallback to xterm
for (auto term : {"xdg-terminal", "x-terminal-emulator", "xterm", "rxvt"}) {
args.insert(args.end(), {::strdup(term),
::strdup("-e")});
// Dup my commad line options to the terminal
for (int i = 0; i < argc; ++i)
args.push_back(::strdup(argv[i]));
args.push_back(nullptr);
execvp(term, args.data());
for (auto arg : args)
free(arg); // strdup calls alloc
args.clear();
}
// We should not be here
exit(1);
}
// Parent process or fork-fail
exit(pid < 0 ? 1 : 0);
}
bool check_gui()
{
auto authority = getenv("XAUTHORITY");
return authority && authority[0] ? true : false;
}
int main(int argc, char **argv)
{
// Check running from the terminal. Re-run in terminal if required.
check_terminal(argc, argv);
// Ceck for GUI session
auto gui = check_gui();
// Regular execution
cout << "Hello, from the terminal!\n";
cout << " is graphical session? " << (gui ? "yes!" : "no") << '\n';
cin.get();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment