comparison terminal.c @ 794:792be135d3af

Spawn a terminal for the debugger when needed if we are not already attached to one
author Michael Pavone <pavone@retrodev.com>
date Sun, 26 Jul 2015 01:11:04 -0700
parents
children 0433fdd9ba66
comparison
equal deleted inserted replaced
793:9aff36a172b2 794:792be135d3af
1 #include <sys/types.h>
2 #include <sys/stat.h>
3 #include <unistd.h>
4 #include <fcntl.h>
5 #include <stdlib.h>
6 #include <stdint.h>
7 #include <signal.h>
8 #include "util.h"
9 #include "terminal.h"
10
11 pid_t child;
12
13 void cleanup_terminal()
14 {
15 kill(child, SIGKILL);
16 unlink(INPUT_PATH);
17 unlink(OUTPUT_PATH);
18 }
19
20 void init_terminal()
21 {
22 static char init_done;
23 if (!init_done) {
24 if (!(isatty(STDIN_FILENO) && isatty(STDOUT_FILENO))) {
25 #ifndef __APPLE__
26 //check to see if x-terminal-emulator exists, just use xterm if it doesn't
27 char *term = system("which x-terminal-emulator > /dev/null") ? "xterm" : "x-terminal-emulator";
28 #endif
29 //get rid of FIFO's if they already exist
30 unlink(INPUT_PATH);
31 unlink(OUTPUT_PATH);
32 //create FIFOs for talking to helper process in terminal app
33 mkfifo(INPUT_PATH, 0666);
34 mkfifo(OUTPUT_PATH, 0666);
35
36 //close existing file descriptors
37 close(STDIN_FILENO);
38 close(STDOUT_FILENO);
39 close(STDERR_FILENO);
40
41 child = fork();
42 if (child == -1) {
43 //error, oh well
44 warning("Failed to fork for terminal spawn");
45 } else if (!child) {
46 //child process, exec our terminal emulator
47 #ifdef __APPLE__
48 execlp("open", "open", "./termhelper", NULL);
49 #else
50 execlp(term, term, "-title", "BlastEm Debugger", "-e", "./termhelper", NULL);
51 #endif
52 } else {
53 //connect to the FIFOs, these will block so order is important
54 open(INPUT_PATH, O_RDONLY);
55 open(OUTPUT_PATH, O_WRONLY);
56 atexit(cleanup_terminal);
57 if (-1 == dup(STDOUT_FILENO)) {
58 fatal_error("failed to dup STDOUT to STDERR after terminal fork");
59 }
60 }
61 }
62
63 init_done = 1;
64 }
65 }