linux编写who命令代码
-
编写Linux的who命令代码可以使用C语言。下面是一个简单的示例代码:
“`c
#include
#include
#include
#include
#includevoid show_info(struct utmp *utbufp)
{
if (utbufp->ut_type == USER_PROCESS) {
printf(“%-8.8s “, utbufp->ut_user);
printf(“%-12.12s “, utbufp->ut_line);
printf(“%12.12s\n”, utbufp->ut_time);
}
}int main()
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);if ((utmpfd = open(UTMP_FILE, O_RDONLY)) == -1) {
perror(UTMP_FILE);
exit(1);
}while (read(utmpfd, ¤t_record, reclen) == reclen) {
show_info(¤t_record);
}close(utmpfd);
return 0;
}
“`这段代码使用了`utmp`结构体和相关的头文件,其中`show_info`函数用于输出用户登录信息,`main`函数打开`/var/run/utmp`文件并逐行读取其中的用户登录记录,然后调用`show_info`函数将信息输出到终端。
请注意,运行这段代码需要有相应的权限,一般您需要使用root账户或者通过sudo命令运行。2年前 -
以下是一种可能的实现方式:
“`c
#include
#include
#include
#include
#include
#include
#include#define SHOWHOST
void show_info(struct utmp *utbufp) {
if (utbufp->ut_type != USER_PROCESS)
return;printf(“%-8.8s”, utbufp->ut_name);
printf(” “);
printf(“%-8.8s”, utbufp->ut_line);
printf(” “);
printf(“%12.12s”, ctime(&(utbufp->ut_tv.tv_sec)));
#ifdef SHOWHOST
printf(” (%s)”, utbufp->ut_host);
#endif
printf(“\n”);
}int main() {
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);if ((utmpfd = open(UTMP_FILE, O_RDONLY)) == -1) {
perror(UTMP_FILE);
exit(1);
}while (read(utmpfd, ¤t_record, reclen) == reclen)
show_info(¤t_record);close(utmpfd);
return 0;
}“`
解释:
– 总体实现主要依赖于 `utmp.h` 头文件,它定义了用于访问用户登录数据库(utmp文件)的结构和函数。
– `show_info` 函数用于打印utmp记录中的信息,包括用户名、终端设备、登录时间和登录主机地址等信息。
– `main` 函数中打开utmp文件,然后在循环中读取记录,并调用 `show_info` 函数打印信息。最后关闭文件并返回。
– 此代码仅仅是展示如何编写一个简单的who命令,可能在某些系统上需要进行适当的适配或修改。请注意,编写这样的实时查询用户登录信息的程序需要适当的权限。在某些系统上,可能需要以root用户身份运行才能读取utmp文件。另外,由于不同的Linux发行版可能在utmp文件的位置或格式上有所不同,因此可能需要进行适当的修改以匹配不同的系统。
2年前 -
在Linux操作系统中,可以使用C语言编写程序来实现`who`命令的功能。下面是一个简单的示例代码:
“`c
#include
#include
#include
#include
#include#define SHOWHOST
void show_info(struct utmp*);
int main()
{
struct utmp current_record;
int utmpfd;
int reclen = sizeof(current_record);if((utmpfd = open(UTMP_FILE, O_RDONLY)) == -1) {
perror(UTMP_FILE);
exit(1);
}while(read(utmpfd, ¤t_record, reclen) == reclen)
show_info(¤t_record);close(utmpfd);
return 0;
}void show_info(struct utmp* utbufp)
{
if(utbufp->ut_type != USER_PROCESS)
return;
printf(“% – 8.8s”, utbufp->ut_name);
printf(” “);
printf(“% – 8.8s”, utbufp->ut_line);
printf(” “);
printf(“%12.12s”, ctime(&utbufp->ut_time) + 4);
printf(” “);
#ifdef SHOWHOST
printf(“(%s)”, utbufp->ut_host);
#endif
printf(“\n”);
}
“`这段代码首先包含了一些需要的头文件,然后定义了一个`show_info`函数用来显示用户登录信息。
在`main`函数中,首先打开`utmp`文件(通常为`/var/run/utmp`),然后循环读取`utmp`文件,并对每条记录调用`show_info`函数展示信息。
`show_info`函数首先检查记录的类型是否为用户进程,然后使用`printf`函数打印用户名、终端名、登录时间,并根据需要打印登录主机信息。
编译该程序并运行后,即可得到类似于`who`命令输出的结果。
2年前