update from main archive 961116
[glibc/history.git] / login / logwtmp.c
blob17c900181f3b453ca617093c23641b8667ea08ca
1 /* Copyright (C) 1996 Free Software Foundation, Inc.
2 This file is part of the GNU C Library.
3 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
5 The GNU C Library is free software; you can redistribute it and/or
6 modify it under the terms of the GNU Library General Public License as
7 published by the Free Software Foundation; either version 2 of the
8 License, or (at your option) any later version.
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 Library General Public License for more details.
15 You should have received a copy of the GNU Library General Public
16 License along with the GNU C Library; see the file COPYING.LIB. If
17 not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA. */
20 #include <errno.h>
21 #include <string.h>
22 #include <unistd.h>
23 #include <utmp.h>
24 #include <sys/file.h>
25 #include <sys/stat.h>
27 void
28 logwtmp (const char *line, const char *name, const char *host)
30 struct utmp ut;
31 struct stat st;
32 size_t written;
33 int fd;
35 /* Open WTMP file. */
36 fd = __open (_PATH_WTMP, O_WRONLY | O_APPEND);
37 if (fd < 0)
38 return;
40 /* Set information in new entry. */
41 memset (&ut, 0, sizeof (ut));
42 #if _HAVE_UT_PID - 0
43 ut.ut_pid = getpid ();
44 #endif
45 #if _HAVE_UT_TYPE - 0
46 ut.ut_type = name[0] ? USER_PROCESS : DEAD_PROCESS;
47 #endif
48 strncpy (ut.ut_line, line, sizeof ut.ut_line);
49 strncpy (ut.ut_name, name, sizeof ut.ut_name);
50 #if _HAVE_UT_HOST - 0
51 strncpy (ut.ut_host, host, sizeof ut.ut_host);
52 #endif
54 #if _HAVE_UT_TV - 0
55 __gettimeofday (&ut.ut_tv, NULL);
56 #else
57 time (&ut.ut_time);
58 #endif
60 /* Try to lock the file. */
61 if (__flock (fd, LOCK_EX | LOCK_NB) < 0 && errno != ENOSYS)
63 /* Oh, oh. The file is already locked. Wait a bit and try again. */
64 sleep (1);
66 /* This time we ignore the error. */
67 __flock (fd, LOCK_EX | LOCK_NB);
70 /* Remeber original size of log file: */
71 if (__fstat (fd, &st) < 0)
72 goto done;
74 /* Write the entry. If we can't write all the bytes, reset the file
75 size back to the original size. That way, no partial entries
76 will remain. */
77 written = __write (fd, &ut, sizeof (ut));
78 if (written > 0 && written != sizeof (ut))
79 ftruncate (fd, st.st_size);
81 done:
82 /* And unlock the file. */
83 __flock (fd, LOCK_UN);
85 /* Close WTMP file. */
86 __close (fd);