【问题标题】:fread(): Unable to read file for /proc/$pid/statusfread(): 无法读取 /proc/$pid/status 的文件
【发布时间】:2019-03-13 16:42:48
【问题描述】:

我正在尝试在函数中读取文件/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() 中包含源代码。
  • 每当您遇到(甚至怀疑)内存问题时,请始终使用 AddressSanitizer 或至少 valgrind 运行您的程序。

标签: c linux-kernel segmentation-fault fread


【解决方案1】:

问题出在您的 getFile() 函数中。 剩下的代码就OK了。

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

【讨论】:

  • 可能分配给(无用的)FILE* 参数并返回垃圾。
猜你喜欢
  • 2016-12-17
  • 1970-01-01
  • 2015-12-15
  • 2016-06-16
  • 2010-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-01
相关资源
最近更新 更多