Exercise
Enhance your understanding and skills by attempting the exercise provided in this lesson!
We'll cover the following
In this exercise, you are to gain some familiarity with the process management APIs about which you just read. Don’t worry – it’s even more fun than it sounds! You’ll, in general, be much better off if you find as much time as you can to write some code, so why not start now?
Questions
-
Write a program that calls
fork()
. Before callingfork()
, have the main process access a variable (e.g.,x
) and set its value to something (e.g.,100
). What value is the variable in the child process? What happens to the variable when both the child and parent change the value ofx
? -
Write a program that opens a file (with the
open()
system call) and then callsfork()
to create a new process. Can both the child and parent access the file descriptor returned byopen()
? What happens when they are writing to the file concurrently, i.e., at the same time? -
Write another program using
fork()
. The child process should print “hello”; the parent process should print “goodbye”. You should try to ensure that the child process always prints first; can you do this without calling wait() in the parent? -
Write a program that calls
fork()
and then calls some form ofexec()
to run the program/bin/ls
. See if you can try all of the variants ofexec()
, including (on Linux)execl()
,execle()
,execlp()
,execv()
,execvp()
, andexecvpe()
. Why do you think there are so many variants of the same basic call? -
Now write a program that uses
wait()
to wait for the child process to finish in the parent. What doeswait()
return? What happens if you usewait()
in the child? -
Write a slight modification of the previous program, this time using
waitpid()
instead ofwait()
. When wouldwaitpid()
be useful? -
Write a program that creates a child process, and then in the child closes standard output (
STDOUT_FILENO
). What happens if the child callsprintf()
to print some output after closing the descriptor? -
Write a program that creates two children, and connects the standard output of one to the standard input of the other, using the
pipe()
system call.
Get hands-on with 1400+ tech skills courses.