c - 读取() : Unable to read file for/proc/$pid/status

标签 c linux-kernel segmentation-fault fread

我正在尝试读取文件 /proc/$pid/status在一个函数中。我可以使用 fopen 打开该文件当我使用 fread() 阅读它时我得到Segmentation fault (core dumped) .

功能:

void getContextSwitches() {
    FILE* fp;

    int pid = getpid();
    char spid[10];
    snprintf(spid, 10, "%d", pid);

    char buffer[3000];
    size_t bytesRead;

    printf("\nPid of the process is: %s", spid);

    char path[50];
    path[0] = '\0';
    strcat(path, "/proc/");
    strcat(path, spid);
    strcat(path, "/status");

    printf("\nPath: %s\n", path);

    fp = getFile(fp, path);

    if(NULL == fp) {
        printf("File status is not read\n");
        exit(1);
    }
    printf("File pointer not null");
    printf("size of buffer: %ld", sizeof(buffer));
    bytesRead = fread(buffer, 1, sizeof(buffer), fp);
    printf("\nIt's not coming here");
    fclose(fp);
}

这是我获得的输出:

Pid of the process is: 85244
Path: /proc/85244/status

File pointer not null
Size of buffer: 3000
Segmentation fault (core dumped)

buffer大小已正确分配,并且 fp不为空。我的代码的其他区域也有类似的功能,并且它们工作得很好。我检查了fread()的签名看起来也不错。

有人可以帮助我理解这背后的问题吗?

最佳答案

问题出在您的 getFile() 函数中。 其余代码没问题。

我怀疑您从 getFile() 返回了无效的 FILE*

关于c - 读取() : Unable to read file for/proc/$pid/status,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52711953/

相关文章:

c - 需要一个工具来检测 C 代码中的内存泄漏

sockets - 第 2 层中的丢包通知

c++ - v4l2 缺少包含,linux vs uapi/linux

c - 段错误(核心转储)和 zlib

c - 函数 ‘fgetc_unlocked’ 的隐式声明,使用 gcc 5.2

c - BGI 错误 :Graphics not initialised(use initgraph). ..在 DOSBOX...Win 7

c - 有没有办法告诉 C 编译器指针没有别名存储?

c - 如何在没有内核源代码树的情况下构建外部内核模块

VirtualBox Ubuntu 11.10 段错误上的 OpenGL GLUT

c - 第二次使用 fgets 时出现段错误