1 /* Copyright (C) 1998, 1999, 2004 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Zack Weinberg <zack@rabi.phys.columbia.edu>, 1998.
4 
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9 
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14 
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, see
17    <http://www.gnu.org/licenses/>.  */
18 
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <limits.h>
22 #include <pty.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <termios.h>
26 #include <unistd.h>
27 #include <sys/types.h>
28 
29 /* Create pseudo tty master slave pair and set terminal attributes
30    according to TERMP and WINP.  Return handles for both ends in
31    AMASTER and ASLAVE, and return the name of the slave end in NAME.  */
32 int
openpty(int * amaster,int * aslave,char * name,const struct termios * termp,const struct winsize * winp)33 openpty (int *amaster, int *aslave, char *name, const struct termios *termp,
34 	 const struct winsize *winp)
35 {
36 #ifdef PATH_MAX
37   char buf[PATH_MAX];
38 #else
39   char buf[512];
40 #endif
41   int master, slave;
42 
43   master = posix_openpt (O_RDWR);
44   if (master == -1)
45     return -1;
46 
47   if (grantpt (master))
48     goto fail;
49 
50   if (unlockpt (master))
51     goto fail;
52 
53   if (ptsname_r (master, buf, sizeof buf))
54     goto fail;
55 
56   slave = open (buf, O_RDWR | O_NOCTTY);
57   if (slave == -1)
58     {
59       goto fail;
60     }
61 
62   /* XXX Should we ignore errors here?  */
63   if(termp)
64     tcsetattr (slave, TCSAFLUSH, termp);
65   if (winp)
66     ioctl (slave, TIOCSWINSZ, winp);
67 
68   *amaster = master;
69   *aslave = slave;
70   if (name != NULL)
71     strcpy (name, buf);
72 
73   return 0;
74 
75  fail:
76   close (master);
77   return -1;
78 }
79 libutil_hidden_def(openpty)
80