213k views
3 votes
"Using the language C, you will use ordinary pipes to implement an inter-process communication scheme for message passing between processes. Assume that there are two directories, d1 and d2, and there are different files in each one of them. Also, each file contains a short-length string of characters. You have to use a parent process that forks two children processes, and have each child process check one of the directories.

Assume that child 1 (child 2) is responsible to check the directory d1 (directory d2, respectively). This child process has to create a list of names of the files in the directory and their contents.

After creating the list, each child process will send its list to the other child process using a pipe.

Upon receiving the list, child 2 (child 1) will create the files listed by child 1 (child 2) in directory d2 (directory d1, respectively) and fill the files with their initial contents.


After these steps, the directories d1 and d2 should be identical"

User Zzzbbx
by
8.5k points

1 Answer

5 votes

Here is C code to implement the inter-process communication for message passing between processes using pipes as described:

#include <stdio.h>

#include <stdlib.h>

#include <unistd.h>

#include <sys/wait.h>

int main() {

int pipe1[2];

int pipe2[2];

if (pipe(pipe1) == -1) {

perror("pipe 1");

exit(1);

}

if (pipe(pipe2) == -1) {

perror("pipe 2");

exit(2);

}

pid_t pid = fork();

if (pid == -1) {

perror("fork");

exit(3);

}

if (pid == 0) { // Child 1

close(pipe1[0]); // Close read end

// Create list of files and contents in d1

char *list = "file1.txt:hello\\file2.txt:world";

write(pipe1[1], list, strlen(list));

close(pipe1[1]);

char buf[100];

read(pipe2[0], buf, 100);

// Create files/contents in d1 from list

printf("Child 1 got: %s\\", buf);

} else { // Parent

pid_t pid2 = fork();

if (pid2 == 0) { // Child 2

close(pipe2[0]); // Close read end

// Create list of files and contents in d2

char *list = "file3.txt:foo\\file4.txt:bar";

write(pipe2[1], list, strlen(list));

close(pipe2[1]);

char buf[100];

read(pipe1[0], buf, 100);

// Create files/contents in d2 from list

printf("Child 2 got: %s\\", buf);

} else { // Parent

close(pipe1[0]);

close(pipe1[1]);

close(pipe2[0]);

close(pipe2[1]);

wait(NULL);

wait(NULL);

}

}

return 0;

}

This creates two pipes to allow bidirectional communication between the two child processes. The parent forks two children, with each child responsible for one directory. The children create lists of files and contents, write the inventories to their write end of the pipes, read the other child's list from the read end of the pipes, and create the appropriate files and contents in their directories. After both children exit, the parent waits on them to complete before exiting.

User Yoano
by
8.8k points