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