c - 使用 ftw 和 process 打印目录大小及其路径名的打印问题

标签 c linux

这是我正在尝试做的事情:

Write a C program using two processes (one parent, one child). Child process goes through entire directory and sends the path of dir along with its size to the parent and the parent prints out the info like this "dir size \tdirpath".

这是我目前所拥有的:

#define _XOPEN_SOURCE 500
#include <ftw.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/wait.h>

static int dirSize = 0;
char *dirPath = NULL;
static int dirInfo(const char *fpath, const struct stat *sb, int tflag, struct FTW *ftwbuf){
    dirSize = sb -> st_size;
    dirPath = fpath;
    return 0;
}

int main(int argc, char *argv[]){
    pid_t processCheck[1];
    int i = 0;
    int pipes[1][2];
    char *directoryPath = argv[1];

    processCheck[1] = fork();
    if(processCheck[1]==0){
        close(pipes[i][0]);
        nftw(directoryPath, dirInfo, 10, FTW_PHYS);
        write(pipes[i][1], &dirSize, sizeof dirSize);
        write(pipes[i][1], &dirPath, sizeof dirPath);
        close(pipes[i][1]);
        exit(0);
    }
    close(pipes[i][1]);
    int childProcessStatus;
    if(WIFEXITED(childProcessStatus)&&WEXITSTATUS(childProcessStatus)==0){
        int v;
        char * d;
        if(read(pipes[i][0], &v, sizeof v) == sizeof(v)){
            printf("%d\t" , v);
        }
        if(read(pipes[i][0], &d, sizeof d) == sizeof(d)){
            printf("%s\n", d);
        }
    }
    close(pipes[i][0]);
    return 0;
}

问题:程序正在编译和运行,但没有打印任何内容。我还需要在父进程中与子进程同时使用 HashMap 、链表或树按目录大小对目录进行排序

最佳答案

最明显的错误是您没有创建管道。您需要在 fork 上方添加此行:

    pipe(pipes[i]);

另一个错误(或者至少 Undefined Behaviour 在大多数情况下是同一件事)是 processCheck 是一个长度为 1 的数组,这意味着当您尝试访问 processCheck[1] 你已经结束了。

关于c - 使用 ftw 和 process 打印目录大小及其路径名的打印问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49177670/

相关文章:

c - 在 C 中的宏中重新定义标签

linux - 如何在 bash 自动完成中只显示一级子目录?

c - 如何找到目标文件之间的依赖关系?

json - 在 Bash 中有效地将 JSON 文件重写为 CSV

c - 查找以字符 X 开头的所有后缀

c - linux中修改注册字符设备中的文件操作

c - 信号处理程序中的 pthread_exit()

linux - gtkbutton字体颜色变化

c - char *val 和 char *** val 有什么区别?

c - 无法使用 ifdef 宏初始化结构内部的数组