This homework is due on Tuesday, February 24, at 11:59:59 PM (Eastern standard time). You must use the submit to turn in your homework like so: submit cs421_jtang hw2 hw2.c
Your program must be named hw2.c, and it will be compiled on Ubuntu 14.04 as follows:
gcc --std=c99 -Wall -o hw2 hw2.cThere must not be any compilation warnings in your submission; warnings will result in grading penalties. In addition, your code must be properly indented and have a file header comment, as described on the coding conventions page.
In this homework, you will write a program that will produce orphan and zombie processes in Linux.
The C program will be divided into several parts as follows. Begin
your program by calling getpid()
and pipe()
, the former to get the process ID
(PID) of your running program and the latter to create
an unnamed pipe. Display the PID to the screen
via printf()
; use
the %zu specifier when printing the value.
Next, call fork()
to create another
process. In the
parent process, close the reading end of the pipe, while in the
child process, close the writing end.
In the parent process, display the PID of its child process. Next,
read in a string from the user via scanf()
.
Meanwhile, in the child process, obtain the PID of its parent
process via getppid()
. (This value should be the same
as the return value from getpid()
from before.) Then
have the child process read from the unnamed pipe; this will block
it.
If the user enters an 'o'
, your program will then
create an orphan. Do this by having the parent process write
an 'o'
to the pipe, and then quit.
This write will unblock the child process. The child
should sleep()
for a second, and then
call getppid()
again. Display both the previous parent
PID and the new parent PID.
You can confirm that init adopted the orphan by running the command ps x | grep init.
If instead the user had entered a 'z'
, your program
will then create a zombie. First, in the parent process open for
reading the file /proc/child_pid/stat,
where child_pid is the PID of the child process. Next, have
the parent write a 'z'
to the pipe, and
then sleep()
for a second.
This write will unblock the child process. The child simply should quit.
The parent resumes from its sleep. For the still open file handle
to /proc/child_pid/stat,
call rewind()
and re-read the third field. Display both
the previous state and new state to standard output.
Here are two sample outputs from running the program:
My pid is 6269.
Child pid is 6270.
Create an 'o'rphan or a 'z'ombie?
(user enters o)
(after a pause)
Old parent pid was 6269, now it is 1.
My pid is 6282.
Child pid is 6283.
Create an 'o'rphan or a 'z'ombie?
(user enters z)
(after a pause)
State of child process was 'S', now it is 'Z'.
'o'
or 'z'
at the scanf()
.
strtok()
or strsep()
to
parse the stat file.
eventfd()
function as an optimization of this software pattern.
Sorry, there is no extra credit available for this assignment.