The use of related functions in C to manipulate utmp files
- 2020-04-02 03:19:48
- OfStack
C getutent() function: get the account login data from the utmp file
The header file:
#include <utmp.h>
Definition function:
struct utmp *getutent(void);
Getutent () is used to read a logon data from the utmp file (/var/run/utmp), which is returned as a utmp structure.
The utmp structure is defined as follows:
struct utmp
{
short int ut_type; //Login type
pid_t ut_pid; //Pid for the login process
char ut_line[UT_LINESIZE]; //Login device name, omit "/dev/"
char ut_id[4]; //Inittab ID
char ut_user[UT_NAMESIZE]; //Login account
char ut_host[UT_HOSTSIZE]; //Login account The name of the remote host
struxt exit_status ut_exit; //The end state of a process when the type is DEAD_PROCESS
long int ut_session; //Sessioc ID
struct timeval ut_tv; //Time record
int32_t ut_addr_v6[4]; //The network address of the remote host
char __unused[20]; //Remain unused
};
There are several types of ut_type:
EMPTY: this is an EMPTY record. RUN_LVL: record changes to the system run-level BOOT_TIME: records the system boot time NEW_TIME: records the time after the system time has changed OLD_TINE: records the time when the system time is changed. INIT_PROCESS: records a process derived from init. LOGIN_PROCESS: logs the login process. USER_PROCESS: records the general process. DEAD_PROCESS: records a finished process. ACCOUNTING: not yet used.
Exit_status structure definition:
struct exit_status
{
short int e_termination; //Process end state
short int e_exit; //Process exit status
};
Refer to gettimeofday() for the structure definition of timeval.
The correlation constant is defined as follows:
UT_LINESIZE 32 UT_NAMESIZE 32 UT_HOSTSIZE 256Return value: returns utmp structure data. If NULL is returned, there is no data or an error has occurred.
Caveat: getutent () in the first call to open when the utmp file, read the data can be used after endutent () to close the the utmp file.
sample
#include <utmp.h>
main()
{
struct utmp *u;
while((u = getutent()))
{
if(u->ut_type == USER_PROCESS)
printf("%d %s %s %s n", u->ut_type, u->ut_user, u->ut_line, u->ut_host);
}
endutent();
}
perform
// means that there are three root accounts logging in /dev/pts/0, /dev/pts/1 and /dev/pts/2 respectively
7 root PTS / 0
7 root PTS / 1
7 root PTS / 2
The C language setutent() function: reads the login data in the utmp file from scratch
The header file:
#include <utmp.h>
Definition function:
void setutent(void);
Setutent () is used to point the read and write address of getutent() back to the beginning of the utmp file.
C language endutent () function: close the file (closed the utmp file)
The header file:
#include <utmp.h>
Definition function:
void endutent(void);
Function description: endutent by getutent () is used to close the utmp file open.
Example: refer to getutent().