Remarks
Exercise 1 - Anne, sister Anne, do you see anything coming?
Write a program doing the following, in order:
- show "MY PID IS <pid>" with printf (no newline) to get the PID: getpid ()
- show "my PID is <pid>" with write (again without newline)
- fork ()
- display "I AM THE <PARENT|CHILD> AND MY PID IS <pid>" with printf (still no new line)
- display "I am the <parent|child> and my PID is" using write (still no new line)
- force the display of all these messages, for example with puts("").
Do you understand why the display is not quite what you expect?
Exercise 2 - Hit the road, Jack
- Set environment variables RUN_0, RUN_1, RUN_2 ...,
then write a program displaying them one after the other. You must use the
getenv() function to retrieve the value of a variable. The program
will display all the variables, until there is one that does not exist, for
example if only RUN_0, RUN_1 and RUN_3 are defined only 0 and 1
have to be printed (as RUN_2 does not exist, the program must stop).
- Using fork() and execvp(), write a program, we will call
mrun, which runs programs present in RUN_0, RUN_1, etc..
with the arguments of the command line. For example, if RUN_0=ls and
RUN_1=cat, then the command "mrun titi.c foo.c" will be the same as
"ls foo.c titi.c ; cat foo.c titi.c". To wait for the termination of
a command before starting the next one, use wait().
Exercise 3 - Fork Accident
- Tricky question: Write a process which, through the system call fork (),
launches 20 processes, each one posting "I'm number <1-20>, my PID is <pid> and my father is <pid>"
(use write() on that shot). Think carefully before you start your program (if you're not careful, you will crash your PC - you have been warned).
- Once the above program works fine, change it so that the parent process, after launching the 20 sons, infinitely loops
(while(1) pause();). With the ps command, list your processes: why the 20 sons are still there, although their execution is complete?
- Use the system call waitpid() to correct the problem in the previous question. For each child process which terminates its execution, display "the process No. <x> with PID <y> just finished."
Exercise 4 - Death Announcement
When a child process ends, the system sends a SIGCHLD signal to the parent process.
Modify the previous exercise to use a signal handler to notify on the standard output of the termination of a child process
(see
man signal()).