Debian Codegraph @

lib/login_tty.c

raw
1 /* Assign a given terminal as controlling terminal and as standard input,
2 standard output, standard error of the current process.
3 Copyright (C) 2010-2026 Free Software Foundation, Inc.
4
5 This file is free software: you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as
7 published by the Free Software Foundation, either version 3 of the
8 License, or (at your option) any later version.
9
10 This file 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
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
17
18 #include <config.h>
19
20 /* Specification. */
21 #include <utmp.h>
22
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <sys/ioctl.h>
26
27 int
28 login_tty (int slave_fd)
29 {
30 /* Create a new session. */
31 setsid ();
32
33 /* Make fd the controlling terminal for the current process.
34 On BSD: There is ioctl TIOCSCTTY for this purpose.
35 On Solaris:
36 A terminal becomes the controlling terminal of a session
37 if it is being open()ed, at a moment when
38 1. it is not already the controlling terminal of some session, and
39 2. the process that open()s it is a session leader that does not have
40 a controlling terminal.
41 We assume condition 1, try to ensure condition 2, and then open() it.
42 */
43 for (int i = 0; i < 3; i++)
44 if (i != slave_fd)
45 close (i);
46 #ifdef TIOCSCTTY
47 if (ioctl (slave_fd, TIOCSCTTY, NULL) < 0)
48 return -1;
49 #else
50 {
51 char *slave_name = ttyname (slave_fd);
52 if (slave_name == NULL)
53 return -1;
54 int dummy_fd = open (slave_name, O_RDWR | O_CLOEXEC);
55 if (dummy_fd < 0)
56 return -1;
57 close (dummy_fd);
58 }
59 #endif
60
61 /* Assign fd to the standard input, standard output, and standard error of
62 the current process. */
63 for (int i = 0; i < 3; i++)
64 if (slave_fd != i)
65 if (dup2 (slave_fd, i) < 0)
66 return -1;
67 if (slave_fd >= 3)
68 close (slave_fd);
69
70 return 0;
71 }