我正尝试在 C 中实现 ps 命令,因此我遇到了很多奇怪的错误。
我的代码:
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/procfs.h>
#include <fcntl.h>
#include <sys/ioctl.h>
int fdproc;
DIR *dirp;
struct dirent *DirEntry;
struct elf_prpsinfo pinfo;
/*
* open the /proc directory for reading process statuses
*/
int main()
{
if ((dirp = opendir("/proc")) == (DIR *)NULL)
{
perror("/proc");
exit(1);
}
/*
* loop for each process in the system
*/
while(DirEntry = readdir(dirp))
{
if (DirEntry->d_name[0] != '.')
{
strcpy(procbuf, "/proc/");
strcat(procbuf, DirEntry->d_name);
}
if ((fdproc = open(procbuf, O_RDONLY)) < 0)
{
continue;
}
/*
* get the ps status for the process
*/
if (ioctl(fdproc, PIOCPSINFO, &pinfo) < 0)
{
close(fdproc);
continue;
}
/* process the pinfo stuff here, see
/usr/include/sys/procfs.h for details */
close(fdproc);
}
}
我在 Internet 上的某个地方找到了这段代码,在完成了我的一些工作之后,我仍然遇到一些奇怪的错误,例如:
‘PIOCPSINFO’ undeclared
‘procbuf’ undeclared
我认为这是 Ubuntu 中预定义的东西。有什么建议吗?
最佳答案
对于你的错误问题:
定义 char *procbuf
然后尝试检查/proc 目录是否已挂载,以便您可以访问或 pid 名称目录属性。另请阅读有关 ioctl 函数的参数 requests 的更多信息,以便您了解方法可以带你进一步解决这个问题。
关于c - 试图在 c 中实现 ps 命令但出现奇怪的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29507553/