Change resize policy
[abduco.git] / forkpty-aix.c
blobff446d38a86ad402c1745be440fbb638c8a1dbda
1 /*
2 * Copyright (c) 2009 Nicholas Marriott <nicm@users.sourceforge.net>
3 * Copyright (c) 2012 Ross Palmer Mohn <rpmohn@waxandwane.org>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
14 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
15 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18 #include <sys/types.h>
19 #include <sys/ioctl.h>
21 #include <fcntl.h>
22 #include <stdlib.h>
23 #include <stropts.h>
24 #include <unistd.h>
25 #include <paths.h>
27 /* Fatal errors. */
28 #ifdef NDEBUG
29 #define debug(format, args...)
30 #else
31 #define debug eprint
32 #endif
33 #define fatal(msg) debug("%s: %s", __func__, msg);
35 pid_t
36 forkpty(int *master, char *name, struct termios *tio, struct winsize *ws)
38 int slave, fd;
39 char *path;
40 pid_t pid;
41 struct termios tio2;
43 if ((*master = open("/dev/ptc", O_RDWR|O_NOCTTY)) == -1)
44 return (-1);
46 if ((path = ttyname(*master)) == NULL)
47 goto out;
48 if ((slave = open(path, O_RDWR|O_NOCTTY)) == -1)
49 goto out;
51 switch (pid = fork()) {
52 case -1:
53 goto out;
54 case 0:
55 close(*master);
57 fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
58 if (fd >= 0) {
59 ioctl(fd, TIOCNOTTY, NULL);
60 close(fd);
63 if (setsid() < 0)
64 fatal("setsid");
66 fd = open(_PATH_TTY, O_RDWR|O_NOCTTY);
67 if (fd >= 0)
68 fatal("open succeeded (failed to disconnect)");
70 fd = open(path, O_RDWR);
71 if (fd < 0)
72 fatal("open failed");
73 close(fd);
75 fd = open("/dev/tty", O_WRONLY);
76 if (fd < 0)
77 fatal("open failed");
78 close(fd);
80 if (tcgetattr(slave, &tio2) != 0)
81 fatal("tcgetattr failed");
82 if (tio != NULL)
83 memcpy(tio2.c_cc, tio->c_cc, sizeof tio2.c_cc);
84 tio2.c_cc[VERASE] = '\177';
85 if (tcsetattr(slave, TCSAFLUSH, &tio2) == -1)
86 fatal("tcsetattr failed");
87 if (ioctl(slave, TIOCSWINSZ, ws) == -1)
88 fatal("ioctl failed");
90 dup2(slave, 0);
91 dup2(slave, 1);
92 dup2(slave, 2);
93 if (slave > 2)
94 close(slave);
95 return (0);
98 close(slave);
99 return (pid);
101 out:
102 if (*master != -1)
103 close(*master);
104 if (slave != -1)
105 close(slave);
106 return (-1);