[英]How to show all users process [with date, parent id, user-name] in Linux?
我在Kubuntu上,但我不想使用任何其他库,只能使用linux函数。我知道这里有一个库http://procps.sourceforge.net/,但这不是重点。 我想打印一个由登录用户拥有的进程,显示其日期,父进程ID和用户名,如何在C中做到这一点?
system("ps -aef | grep username");
将获得用户拥有的所有进程。
这些信息存储在/proc
:每个进程都有自己的目录,称为PID。
您将需要遍历所有这些目录并收集所需的数据。 ps
就是这样做的。
我认为您必须扫描/proc
文件夹。 我将给你一个关于如何开始的想法。 抱歉,但是我没有时间完整编码您的请求=(
(看看这里的/proc/[pid]/stat
部分来发现统计文件是如何被格式化)
while((dirEntry = readdir("/proc")) != NULL)
{
// is a number? (pid)
if (scanf(dirEntry->d_name, "%d", &dummy) == 1)
{
// get info about the node (file or folder)
lstat(dirEntry->d_name, &buf);
// it must be a folder
if (buf.st_mode != S_IFDIR)
continue;
// check if it's owned by the uid you need
if (buf.st_uid != my_userid)
continue;
// ok i got a pid of a process owned by my user
printf("My user own process with pid %d\n", dirEntry->d_name);
// build full path of stat file (full of useful infos)
sprintf(stat_path, "/proc/%s/stat", dirEntry->d_name;
// self explaining function (you have to write it) to extract the parent pid
parentpid = extract_the_fourth_field(stat_path);
// printout the parent pid
printf("parent pid: %d\n", parentpid);
// check for the above linked manual page about stat file to get more infos
// about the current pid
}
}
我建议阅读/proc
。 proc文件系统是Linux中实现的最佳文件系统。
如果没有,您可以考虑编写一个内核模块,该模块将实现您自己的系统调用(以获取当前进程的列表),以便可以从用户空间程序中对其进行调用。
/* ProcessList.c
Robert Love Chapter 3
*/
#include < linux/kernel.h >
#include < linux/sched.h >
#include < linux/module.h >
int init_module(void)
{
struct task_struct *task;
for_each_process(task)
{
printk("%s [%d]\n",task->comm , task->pid);
}
return 0;
}
void cleanup_module(void)
{
printk(KERN_INFO "Cleaning Up.\n");
}
上面的代码来自此处的文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.