C语言实现linux之who功能
2024-10-20 06:16:01
/*
who_test.c
*/
#include<stdio.h>
#include<string.h>
#include<getopt.h>
#include<time.h>
#include<stdlib.h>
#include<stdbool.h>
#include<utmp.h> //设置标志位,用来标志命令行参数
bool opt_H = false;
bool opt_q = false; /**mywho函数是调用系统数据文件的核心程序;
***它首先调用系统数据文件的接口函数,然后逐条将其数据保存下来;
***根据选项的标记为,然后输出不同的信息
***关闭系统数据文件
***/
static int mywho()
{
/*
*在系统的数据文件中,提供两个文件 utmp 和 wtmp 两个文件
* 这两个文件记录的数据结构就是utmp, 所以要声明一个utmp数据结构
*/
struct utmp *um;
char timebuf[];
int users = ; //当命令选型为 -q, 用来保存用户数量 if (opt_q)
{
/** getutent 函数用来读下一条记录,如果需要,还会打开该文件。
*返回一个指向 utmp 的指针。
*/
while ((um == getutent()))
{ if (um->ut_type != USER_PROCESS) /* 利用 utmp 结构的ut_type域,过滤出普通进程 */
{
continue;
}
printf("%-2s ", um->ut_user);
users += ;
} printf("\n# users = %d\n", users);
endutent();
return ;
} //打印各栏标题头部
if (opt_H)
{
printf("%-12s%-12s%-20.20s %s\n","NAME", "LINE", "TIME", "COMMENT");
} //此处处理的是 utmp 文件的内容
while ((um = getutent()))
{
// 利用 utmp 结构的ut_type域,过滤出普通进程
if (um->ut_type != USER_PROCESS)
{
continue;
} time_t tm;
tm = (time_t)(um->ut_tv.tv_sec);
strftime(timebuf, , "%F %R", localtime(&tm));
printf("%-12s%-12s%-20.20s (%s)\n", um->ut_user, um->ut_line, timebuf, um->ut_host);
} endutent();
return ;
} int main(int argc, char **argv)
{
int c;
int ok; while ((c = getopt(argc, argv, "Hqb")) != -)
{
switch(c)
{
case 'H':
opt_H = true;
break;
case 'q':
opt_q = true;
break;
default:
exit();
}
} if (argc != optind)
{
printf("fault command! \n");
} ok = mywho(); if (!ok)
{
return ;
}
else
{
exit();
} }
运行结果:
最新文章
- Linux搭建Nginx
- Android之计算缓存大小并且清空缓存
- Quill – 可以灵活自定义的开源的富文本编辑器
- Linux服务器下nginx的安全配置
- 让Xcode的控制台支持LLDB类型的打印
- 文字的多列布局--column
- POJ 3974	Palindrome
- php socket 学习
- python 内存管理
- 2.1孙鑫C++
- sublime_text编辑器下载安装使用
- Yii modules中layout文件的调用
- SSH Secure Shell Client连接Linux 命令行显示中文乱码问题 和oracle 查询数据中文乱码问题
- mysql 根据规定的数组进行排序
- Iterator(迭代器模式)--(超市管理者)
- hdu_5778_abs(暴力)
- AngularJS学习篇(十三)
- 用SpriteBuilder简化";耕牛遍地走";的动画效果(三)
- request.getRequestDispatcher跳转jsp页面失败
- [模板] K-D Tree
热门文章
- WPF DataGrid横向显示
- mysql解决Fatal error encountered during command execution. 500内部错误
- JS面向对象设计-创建对象
- 如何设计提高服务API的安全性(一)基础介绍
- 触发器TRIGGER 自增IDENTITY 聚集索引CLUSTERED
- C# Net 合并int集合为字符串,如:输入1,2,3,4,8 输出1~4,8
- Firefox火狐浏览器打开新标签页一直闪烁
- Oracle ASMCMD命令参考
- 1 NLP学习大纲
- 通过async实现协程的延迟执行及结果获取