linux - 无法从 C linux 中的/proc 位置打开文件夹

标签 linux api proc

我将读取/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 控制台登录:

enter image description here

最佳答案

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

您可以使用类似的方法来格式化路径:

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

适本地设置路径格式。

关于linux - 无法从 C linux 中的/proc 位置打开文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38543170/

相关文章:

python - 如何手动清理主目录中的 conda?

javascript - 如何在React Native中获取选定的元素?

api - PayPal REST API - 从沙盒转移到生产环境

android - 如何找到我在android ndk中拥有pid的进程的cpu使用情况

c - fork后Printf无法在父级和子级中打印

linux - 在 debian 上重建包和包管理器

linux - 如何在 Raspberry Pi 上使用 gdbserver?

api - GOOGLE DOCS API 无效请求[0].updateTextStyle : Index 4 must be less than the end index of the referenced segment, 2.",

c - 无法使用 Oracle 12C 在 Redhat Linux 中重新编译遗留 Pro*C 软件

c - 主线程调用pthread_exit后,它变成了僵尸。出了什么问题吗?