alot of renaming...
[k8sterm.git] / src / ttyinit.c
blob4d253095dc01eba974540c5aa43459ff23bbc04f
1 ////////////////////////////////////////////////////////////////////////////////
2 // tty init
3 /*
4 static void dump (char c) {
5 static int col;
6 //
7 fprintf(stderr, " %02x '%c' ", c, isprint(c)?c:'.');
8 if (++col % 10 == 0) fprintf(stderr, "\n");
13 static __attribute__((noreturn)) void execsh (const char *str) {
14 char **args;
16 if (str == NULL) {
17 char *envshell = getenv("SHELL");
19 K8T_DEFAULT(envshell, opt_shell);
20 setenv("TERM", opt_term, 1);
21 args = opt_cmd ? opt_cmd : (char *[]){envshell, "-i", NULL};
22 } else {
23 int argc = 0;
25 args = calloc(32768, sizeof(char *));
26 if (args == NULL) exit(EXIT_FAILURE);
27 while (*str) {
28 const char *b;
30 while (*str && isspace(*str)) ++str;
31 if (!str[0]) break;
33 b = str;
34 while (*str && !isspace(*str)) {
35 if (*str++ == '\\') {
36 if (*str) ++str;
40 args[argc] = calloc(str-b+1, 1);
41 memcpy(args[argc], b, str-b);
44 FILE *fo = fopen("z.log", "a");
45 fprintf(fo, "%d: [%s]\n", argc, args[argc]);
46 fclose(fo);
49 ++argc;
51 if (argc < 1) exit(EXIT_FAILURE);
53 execvp(args[0], args);
54 exit(EXIT_FAILURE);
58 static int k8t_ttyNew (K8Term *term) {
59 int m, s;
60 struct winsize w = {term->row, term->col, 0, 0};
62 if (openpty(&m, &s, NULL, NULL, &w) < 0) die("openpty failed: %s", strerror(errno));
63 term->cmdfd = m;
64 k8t_ttyResize(term);
65 term->cmdfd = -1;
66 switch (term->pid = fork()) {
67 case -1: /* error */
68 fprintf(stderr, "fork failed");
69 return -1;
70 case 0: /* child */
71 setsid(); /* create a new process group */
72 dup2(s, STDIN_FILENO);
73 dup2(s, STDOUT_FILENO);
74 dup2(s, STDERR_FILENO);
75 if (ioctl(s, TIOCSCTTY, NULL) < 0) die("ioctl TIOCSCTTY failed: %s", strerror(errno));
76 close(s);
77 close(m);
78 execsh(term->execcmd);
79 break;
80 default: /* master */
81 close(s);
82 term->cmdfd = m;
83 term->dead = 0;
84 k8t_ttyResize(term);
85 break;
87 return 0;