My code :
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);
when run, console show :
parent process
Child process 1 counted 15340 lines
Child process 3 counted 8866 lines
Child process 2 counted 5361 lines
Child process 0 counted 7089 lines
Total lines in the file: 816
Total lines not show real total lines in the file. How to show real total lines in the file for this case use fork?
When you call
exit(lines)the parent process will receivelines & 0xFFwhich is at most 255 on Linux. When the client needs to communicatelinesback to the parent process use a different IPC mechanism like pipe, message queue, shared memory segment (shmget,shmget), memory mapped file (mmap), socket etc.A particular easy way to understand is for parent and child to agree on a path that the client is going to write the data, say,
lines.<pid>. Client can get it's own pid withgetpid()and the server already has it from the return value offork().