在 c 中使用 fork 的文件总行数

问题描述 投票:0回答:1

我的代码:

char *filename = "/home/septian/Documents/Repository.cs";
FILE *file = fopen(filename, "r");

if (file == NULL) {
    perror("File open failed");
    return 1;
}

int num_processes = 4; // Number of child processes to create
pid_t pid[num_processes];

for (int i = 0; i < num_processes; i++) {
    pid_t child_pid = fork();

    if (child_pid < 0) {
        perror("Fork failed");
        return 1;
    } else if (child_pid == 0) {
        // This code runs in the child process
        int lines = 0;
        char ch;
        fseek(file, 0, SEEK_SET); // Rewind the file to the beginning

        // Read the file and count lines
        while ((ch = fgetc(file)) != EOF) {
            if (ch == '\n') {
                lines++;
            }
        }

        **printf("Child process %d counted %d lines\n", i, lines);
        exit(lines); // Terminate the child process with the line count**
    } else {
        pid[i] = child_pid; // Store child process IDs in an array
    }
}

// This code runs in the parent process
printf("parent process\n");
int total_lines = 0;
for (int i = 0; i < num_processes; i++) {
    int status;
    waitpid(pid[i], &status, 0); // Wait for child processes to finish
    total_lines += WEXITSTATUS(status);
}

printf("Total lines in the file: %d\n", total_lines);
fclose(file);

运行时,控制台显示:

父进程

子进程1计数为15340行

子进程3计数为8866行

子进程 2 计数为 5361 行

子进程 0 计数为 7089 行

文件总行数:816

总行数不显示文件中的真实总行数。 在这种情况下,如何使用 fork 显示文件中的真实总行数?

c++ c operating-system fork pid
1个回答
0
投票

当您调用

exit(lines)
时,父进程将收到
lines & 0xFF
,至少在 Linux 上最多为 255。您需要通过另一个 IPC 机制(如
pipe
)将数据传回父进程。

© www.soinside.com 2019 - 2024. All rights reserved.