Description
Homework #4
The intention of this homework is to understand process creation and pipes in Linux and to practice programming in Linux.
Problem Statement
D.R. Kaprekars Operation, a process named after Indian mathematician D.R. Kaprekar, is described as follows.
Given any three- or four-digit number where not all digits are the same, i.e., not 111, 8888, etc.,
1. Rearrange the digits of the number in descending and ascending orders in order to make the largest and smallest numbers out of those digits. For example, given 2418, the largest number using these four digits is 8421 and the smallest one is 1248.
2. Subtract the smaller number from larger one.
- 3. Take the result from step 2. Go to step 1 and repeat the process until the result converges.
- Given the number 5438, the Kaprekars process is:
- 8543-3458 = 5085 8550-558 = 7992 9972-2799 = 7173 7731 – 1377 = 6354 6543 – 3456 = 3087 8730-378 = 8352 8532-2358 = 6174 7641-1467 = 6174
- 7641-1467 = 6174
- (converged)
- For any 3-digit number where not all digits are the same, the final result will be 495!
Requirement
Write a C program using the fork() system call to create a child process that executes Kaprekars Operation for a 3-digt number. The child process is required to print out the intermediate results as shown in the example above. The input number should be provided from the command line. For consistency, use the number 123 as the testing input.
In addition, the child process should inform the parent process about the completion of the operation, i.e., when the operation converges to a fixed number. This is done by sending the final converged number to the parent process using an ordinary pipe (refer to figure 3.25-3.26 for pipe creation). Upon receiving the message from the child, the parent process is required to print out the message. Have the parent invoke the wait() call to wait for the child process to complete before exiting the program.
Steps:
- Download the incomplete source file hw4.c. The incomplete code obtains the input number and assigns it to variable n.
Complete the code
Compile the C source file using gcc. This is similar to our preparation homework.
Take a screenshot of the program intermediate results and final output (see screenshot 1 below as a sample output).