我在Kubuntu,但我不想使用任何其他的libs,我只能使用linux函数。我知道有一个库http://procps.sourceforge.net/,但这不是重点。我想打印一个由登录用户拥有的进程,显示他们的日期,父进程ID和用户名,如何在C中执行?
答案 0 :(得分:1)
system("ps -aef | grep username");
将获得用户拥有的所有进程。
答案 1 :(得分:1)
这些信息存储在/proc
中:每个进程都有自己的目录,其名称为PID。
您需要遍历所有这些目录并收集所需的数据。这就是ps
所做的。
答案 2 :(得分:1)
我认为您必须扫描/proc
文件夹。我打算给你一个关于如何开始的想法。抱歉,我没有时间完整编码您的请求=(
(在/proc/[pid]/stat
部分查看here以了解统计信息的格式化方式)
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
}
}
答案 3 :(得分:1)
我建议从/proc
阅读。 proc filesystem是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");
}
上述代码摘自文章here。