Question
Programming Language: C++ (SIMPLE Program) fork() Refer to the manual pages for the proper use of the fork() function. The fork() function creates a new
Programming Language: C++ (SIMPLE Program)
fork()
Refer to the manual pages for the proper use of the fork() function. The fork() function creates a new process that is essentially an exact copy of the calling process. The new process is called the child process while the calling process is called the parent process. Both processes continue executing the program image at the point immediately after the call to fork(). In the case of the child, the call to fork() returns a 0. In the case of the parent, the call to fork() returns either the process ID of the newly created child process or a negative value indicating that the call failed and no child process was created. The skeleton code below illustrates the proper use of fork(). Note the inclusion of the
#include
::
main()
{
pid_t pid;
pid = fork();
if (pid == 0)
{
//child process continues here
::
}
else
{
//parent process continues here
::
}
}
Use the skeleton code above to write a program that spawns 10 child processes then quits, leaving the children to continue running. For each child process, the parent should output a process number. So, the parents output should look something like this:
Child 1s PID is ####.
Child 2s PID is ####.
Child 3s PID is ####.
Child 4s PID is ####.
Child 5s PID is ####.
Child 6s PID is ####.
Child 7s PID is ####.
Child 8s PID is ####.
Child 9s PID is ####.
Child 10s PID is ####.
Once the parent finishes, you should be returned to the prompt. Note the PID of each child process (a cell phone picture or screen capture may help here). Each child processes should identify itself every 10 seconds in an infinite loop with an output line similar to the following:
I am process N.
Use the sleep() function to create the delay. Verify that while the parent process has stopped running (you are back at the prompt), all 10 of the children processes keep producing output. Use the top program to view running processes (if you are on a graphical screen, you may need to expand the window horizontally to see the complete output of top).
Now, using the process PIDs printed by the parent, kill the even number processes with the kill command from the command line. If the child process ID is N, for example, the command
kill N
will kill the child with process ID N.
Verify that only the expected processes continue to broadcast their IDs:
I am process 1.
I am process 3.
I am process 5.
I am process 7.
I am process 9.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started