commit 45415eb

uint  ·  2026-06-23 15:27:26 +0000 UTC
parent 5026e5f
Move pty spawing, running logic to functions
1 files changed,  +36, -29
M tmtm.c
M tmtm.c
+36, -29
  1@@ -19,10 +19,11 @@ static void die(int ln, int ec, const char* fmt, ...);
  2 static void getwinsize(void);
  3 static void rawon(void);
  4 static void rawoff(void);
  5+static void run(void);
  6+static void spawnpty(void);
  7 
  8 static struct termios orig_termios;
  9-static int scrrows = 0;
 10-static int scrcols = 0;
 11+static struct winsize ws;
 12 static int masterfd = -1;
 13 
 14 static void die(int ln, int ec, const char* fmt, ...)
 15@@ -63,37 +64,13 @@ static void rawoff(void)
 16 
 17 static void getwinsize(void)
 18 {
 19-	struct winsize ws;
 20 	if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == -1 || ws.ws_col == 0)
 21 		die(__LINE__, EXIT_FAILURE, "failed to get window size");
 22-	scrrows = ws.ws_row;
 23-	scrcols = ws.ws_col;
 24 }
 25 
 26-int main(int argc, char* argv[])
 27+static void run(void)
 28 {
 29-	if (argc > 1) {
 30-		if (strcmp("-v", argv[1]) == 0) {
 31-			printf("tmtm v%s", TMTM_VER);
 32-			return EXIT_SUCCESS;
 33-		}
 34-	}
 35-
 36-	pid_t pid = forkpty(&masterfd, NULL, NULL, NULL);
 37-	if (pid < 0)
 38-		die(__LINE__, EXIT_FAILURE, "forkpty failed");
 39-	if (pid == 0) {
 40-		char* shell = getenv("SHELL");
 41-		if (!shell)
 42-			shell = "sh";
 43-		execlp(shell, shell, NULL);
 44-		fprintf(stderr, "ln:%d execlp failed", __LINE__);
 45-		_exit(EXIT_FAILURE);
 46-	}
 47-
 48-	rawon();
 49-	getwinsize();
 50-
 51+	spawnpty();
 52 	struct pollfd fds[2]; /* stdin, shell */
 53 	fds[0].fd = STDIN_FILENO;
 54 	fds[0].events = POLLIN;
 55@@ -111,7 +88,7 @@ int main(int argc, char* argv[])
 56 			int n = read(STDIN_FILENO, buf, sizeof(buf));
 57 			if (n <= 0)
 58 				break;
 59-			if (n == 1 && buf[0] == 0x11) /* ctrl-q */
 60+			if (n == 1 && buf[0] == 0x0E) /* TODO ctrl-n */
 61 				break;
 62 			if (write(masterfd, buf, n) < 0)
 63 				break;
 64@@ -133,6 +110,36 @@ int main(int argc, char* argv[])
 65 
 66 	printf("\r\nexited pty\r\n");
 67 
 68+}
 69+
 70+static void spawnpty(void)
 71+{
 72+	pid_t pid = forkpty(&masterfd, NULL, NULL, &ws);
 73+	if (pid < 0)
 74+		die(__LINE__, EXIT_FAILURE, "forkpty failed");
 75+	if (pid == 0) {
 76+		char* shell = getenv("SHELL");
 77+		if (!shell)
 78+			shell = "sh";
 79+		execlp(shell, shell, NULL);
 80+		fprintf(stderr, "ln:%d execlp failed", __LINE__);
 81+		_exit(EXIT_FAILURE);
 82+	}
 83+}
 84+
 85+int main(int argc, char* argv[])
 86+{
 87+	if (argc > 1) {
 88+		if (strcmp("-v", argv[1]) == 0) {
 89+			printf("tmtm v%s", TMTM_VER);
 90+			return EXIT_SUCCESS;
 91+		}
 92+	}
 93+
 94+	rawon();
 95+	getwinsize();
 96+	run();
 97+
 98 	return EXIT_SUCCESS;
 99 }
100