Design and implement a program in c++ using unix/linux machine that uses fork an
ID: 3601155 • Letter: D
Question
Design and implement a program in c++ using unix/linux machine that uses fork and pipe to create processes to add all numbers in a file. The user will enter a number (1, 2, or 4) of parallel processes to create for processing the numbers. The system will then create this many processes, evenly dividing the file contents between the processes. For example, if the file has 1000 numbers and the user wants 4 processes, then each process would process 250 numbers in the file.
Parent process. This process allows user to input the number of processes to create (1, 2, or 4). It determines what portion of the file each process must work on and informs the process via a pipe. More specifically, the first child process handles the first block in the file, and the second child process handles the second one and so on. The parent then waits for each child to report its result. Once each result is received, it combines the results prints the overall result.
Child process. Receive which part of the file to calculate from the parent process through pipe. Process the file and send the result back to the parent process through pipe.
There are 4 given files named file1.dat, file2.dat, file3.dat, file4.dat
this program should output the result and record the run time for each process 1,2, and 4
Explanation / Answer
Redirections
$ cmd1 > stdout.txt
The above command redirects stdout to file stdout.txt
For implementing the above operation, we should be able to link stdout of cmd1 with file descriptor of stdout.txt opened with write mode. Let us look at the code.
$ cmd1 2> stdout.txt
The above command redirects stderr to file stdout.txt
$ cmd2 > stdout_stderr.txt 2>&1
The above command redirects both stdout and stderr to file stdout_stderr.txt
$ cmd3 < input.txt
The above command redirects data from input.txt to stdin for cmd3.
Pipe
$ cmd1 | cmd2
This command says that cmd2 will receive stdin from stdout of cmd1.
1 2 3 4 5 6 7 8 9
main(){ close(1); // Release fd no - 1 open("stdout.txt", "w"); // Open a file with fd no = 1 // Child process if (fork() == 0) { exec("cmd1"); // By default, the program writes to stdout (fd no - 1). ie, in this case, the file } } Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.