nxu/term.c

58 lines
1.5 KiB
C
Raw Permalink Normal View History

2023-02-04 18:48:06 -05:00
#include <pwd.h>
#ifdef __APPLE__
#include <util.h>
#include <sys/ioctl.h>
#else
2023-01-25 23:37:56 -05:00
#include <pty.h>
2023-02-04 18:48:06 -05:00
#endif
2023-01-25 23:37:56 -05:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
2023-02-04 16:39:44 -05:00
// compile with gcc term.c -lutil
2023-01-25 23:37:56 -05:00
int main(int argc, char **argv) {
if (argc < 2) {
2023-02-04 18:48:06 -05:00
printf("usage: %s ROM [LOGIN]\n", argv[0]);
2023-01-25 23:37:56 -05:00
return 1;
}
2023-02-04 16:32:59 -05:00
char *rom = argv[1]; // find term.rom
2023-02-04 18:48:06 -05:00
int login = argc > 2; // any extra arg signals login shell
// detect the user's shell
char *shell = getenv("SHELL");
if (shell == NULL) {
struct passwd *passwd = getpwuid(getuid());
if (passwd != NULL) {
shell = passwd->pw_shell;
}
}
if (shell == NULL) {
shell = "/bin/sh";
}
2023-02-04 16:32:59 -05:00
// allocate a pty, fork, inititialize file descriptor
2023-02-04 18:48:06 -05:00
int fdm = -1; // allocate file descriptor
2023-02-04 18:16:29 -05:00
pid_t pid = forkpty(&fdm, NULL, NULL, NULL);
2023-02-04 16:32:59 -05:00
if (pid < 0) { // failure
2023-02-04 16:34:05 -05:00
perror("fork failed");
2023-02-04 16:02:21 -05:00
return 1;
2023-02-04 16:32:59 -05:00
} else if (pid == 0) { // child
setenv("TERM", "ansi", 1);
2023-02-04 18:48:06 -05:00
// execute shell
if (login) {
2023-02-05 00:43:36 -05:00
execlp(shell, shell, "-l", "-i", NULL);
2023-02-04 18:48:06 -05:00
} else {
2023-02-05 00:43:36 -05:00
execlp(shell, shell, NULL);
2023-02-04 18:48:06 -05:00
}
2023-02-04 16:34:05 -05:00
perror("exec bash failed");
2023-02-04 16:32:59 -05:00
} else { // parent
struct winsize ws = {23, 80, 8, 12}; // rows, cols, xps, ypx
ioctl(fdm, TIOCSWINSZ, &ws); // set term window size
dup2(fdm, 0); // use fdm for stdin
dup2(fdm, 1); // use fdm for stdout
execlp("uxnemu", "uxnemu", rom, NULL); // exec uxnemu
2023-02-04 16:34:05 -05:00
perror("exec uxnemu failed");
2023-01-25 23:37:56 -05:00
}
}