Rewritten.
[glibc.git] / sysdeps / unix / getlogin.c
blob504a7aa4c0c27d08c2770dab78ecc5d3c9601df8
1 /* Copyright (C) 1991, 1992 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
4 The GNU C Library is free software; you can redistribute it and/or
5 modify it under the terms of the GNU Library General Public License as
6 published by the Free Software Foundation; either version 2 of the
7 License, or (at your option) any later version.
9 The GNU C Library is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 Library General Public License for more details.
14 You should have received a copy of the GNU Library General Public
15 License along with the GNU C Library; see the file COPYING.LIB. If
16 not, write to the Free Software Foundation, Inc., 675 Mass Ave,
17 Cambridge, MA 02139, USA. */
19 #include <ansidecl.h>
20 #include <stddef.h>
21 #include <errno.h>
22 #include <unistd.h>
23 #include <string.h>
24 #include <stdio.h>
25 #include <limits.h>
26 #include <fcntl.h>
28 #include <utmp.h>
30 /* Defined in ttyname.c. */
31 extern char *__ttyname;
33 /* Return the login name of the user, or NULL if it can't be determined.
34 The returned pointer, if not NULL, is good only until the next call. */
36 char *
37 DEFUN_VOID(getlogin)
39 char save_tty_pathname[2 + 2 * NAME_MAX];
40 char *save_ttyname;
41 char *real_tty_path;
42 char *result = NULL;
43 FILE *f;
44 static struct utmp ut;
46 if (__ttyname == NULL)
47 save_ttyname = NULL;
48 else
49 save_ttyname = strcpy (save_tty_pathname, __ttyname);
52 int err;
53 int d = __open ("/dev/tty", 0);
54 if (d < 0)
55 return NULL;
57 real_tty_path = ttyname (d);
58 err = errno;
59 (void) close (d);
61 if (real_tty_path == NULL)
63 errno = err;
64 return NULL;
68 real_tty_path += 5; /* Remove "/dev/". */
70 f = fopen ("/etc/utmp", "r");
71 if (f != NULL)
73 while (fread ((PTR) &ut, sizeof(ut), 1, f) == 1)
74 if (!strncmp (ut.ut_line, real_tty_path, sizeof (ut.ut_line)))
76 result = ut.ut_name;
77 /* The name is not null-terminated if
78 it is as long as sizeof (ut.ut_name). */
79 result[sizeof (ut.ut_name)] = '\0';
80 break;
82 (void) fclose (f);
85 if (save_ttyname != NULL)
86 strcpy (__ttyname, save_ttyname);
87 if (result == NULL)
88 errno = ENOENT;
89 return result;