【发布时间】:2015-04-08 06:34:38
【问题描述】:
我正在尝试在 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);
}
}
我在互联网的某个地方找到了这段代码,在做了一些我的工作之后,我仍然遇到一些奇怪的错误,例如:
‘PIOCPSINFO’ undeclared
‘procbuf’ undeclared
我认为这是在 Ubuntu 中预定义的。有什么建议吗?
【问题讨论】:
-
procbuf 是 C++,因此您需要将任何访问它的代码编译为 C++。例如:opensource.apple.com/source/gcc/gcc-934.3/libio/procbuf.h
-
如果要使用c,定义char *procbuf;然后使用 calloc 和 realloc 动态分配一个大小为 strlen(dirent->name)+1+6; 的数组; , nul 字节和 /proc/.您的 strcat 行交换 DirEntry 到 dirent 也有一个错误
标签: c ubuntu compiler-errors ps