C语言 使用 ftw 和进程打印目录大小及其路径名的打印问题



这是我正在尝试做的:

使用两个进程(一个父进程,一个子进程)编写 C 程序。子进程遍历整个目录,并将 dir 的路径及其大小发送给父进程,父进程打印出类似"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("%dt" , v);
}
if(read(pipes[i][0], &d, sizeof d) == sizeof(d)){
printf("%sn", d);
}
}
close(pipes[i][0]);
return 0;
}

问题:程序正在编译并运行,但未打印任何内容。此外,我还需要使用哈希映射、链表或父进程中的树与子进程同时按目录的大小对目录进行排序

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

pipe(pipes[i]);

另一个错误(或至少是在大多数情况下是同一回事的未定义行为)是processCheck是一个长度为 1 的数组,这意味着当您尝试访问processCheck[1]时,您已经过了它的终点。

最新更新