gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:21 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com