【问题标题】:trying to implement ps command in c but getting strange errors试图在 c 中实现 ps 命令但出现奇怪的错误
【发布时间】: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


【解决方案1】:

对于您的错误问题:
定义字符 *procbuf
然后尝试检查 /proc 目录是否已挂载,以便您可以访问或 pid 名称目录属性。还请阅读有关 ioctl 函数的参数 requests 的更多信息,以便您了解什么方法可以带你进一步解决这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 2019-10-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多