【问题标题】:Can't open folders from /proc location in C linux无法从 C linux 中的 /proc 位置打开文件夹
【发布时间】:2016-07-23 15:03:16
【问题描述】:

我将读取 /proc 的每个目录中的“comm”文件。我的程序可以看到目录列表,但是当我尝试打开此目录中的文件夹时出现错误。我的系统是 Debian Linux 硬件 Beaglebone Black。我正在学习linux下的编程,所以我有很多问题(有时很愚蠢)。

代码列表:

#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>

#include <string.h>
#include <fcntl.h>

int main()
{  
    char path[50] = {0};
    register struct dirent *dirbuf;
    char* dirname = "/proc";
    DIR *fdir;

    fdir = opendir(dirname);
    if (NULL == fdir)
    {  
        printf("Can't open %s\n", dirname);
        return;
    }  

    while(( dirbuf = readdir(fdir)) != NULL)
    {  
        if ((strcmp(dirbuf->d_name, ".") == 0)||(strcmp(dirbuf->d_name, "..") == 0))
        {  
            continue;
        }  

        printf("folder name: %s\n", dirbuf->d_name);
        strcat(path, dirbuf->d_name);
        strcat(path, "/comm");
        printf("path: %s\n", path);

        int fd = open(path, O_RDONLY);
        if ( -1  == fd)
        {  
            printf("Can't open file %s\n", path);
        }  
        else
        {  
            //read file
            close(fd);
        }  
        memset(path, 0, strlen(path) + 1); //clear path buffer

    }  
    closedir(fdir);
    return 0; 
}

来自 linux 控制台的日志:

【问题讨论】:

  • 此函数失败时,设置errno。添加#include 并将errno值添加到打印中,这样你就知道它为什么失败了

标签: linux api proc


【解决方案1】:

您需要使用完整路径来打开文件。即:/proc/PID/comm 而不是PID/comm

你可以使用这样的东西来格式化路径:

char* path[PATH_MAX];
snprintf(path, PATH_MAX, "/proc/%s/comm", dirbuf->d_name);

适当地格式化路径。

【讨论】:

  • 谢谢!还有一个问题。由于 dirbuf->d_name 没有 \0 (end of string) ,我是否需要手动添加“/proc/%s/comm”路径末尾的 \0 ?
  • 对不起,我发现路径默认会有\0。
  • 不,你没有。 snprintf 为您添加 \0。详情见man snprintf
猜你喜欢
  • 2014-05-03
  • 2014-10-12
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2015-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多