Tutorial #3

Topics covered:

Brief system call notes:

exit():

#include <stdlib.h>

void exit(int status);

Terminates the current process, exit never returns. The lower 8 bits of status can be retrieved by a wait()'ing parent. Typically should only be used to end a process in case of errors. exit() does do some cleanup, e.g allocated memory is freed however be careful to free any other resources your process may have allocated - see the man page for details on what exit does cleanup.

 

wait() and waitpid()

#include <sys/types.h>
#include <sys/wait.h>

pid_t wait(int *status)
pid_t waitpid(pid_t pid, int* status, int options)

Blocks until child exits or signal delivered to either kill this process or call a signal handler.

Returns immediately if the child has already exited (a zombie), system resources used by the child (entry in the process table) are then freed.

If you don't wait() or waitpid() for your children then when they die they become zombies taking up space in the process table.

waitpid(pid_t pid, int* status, int options)
pid:

See the man page for the different options flags.
WNOHANG - returns immediately

Evaluating value of status:

Need to use macros to evaluate the meaning of status, again see man page

WIFEXITED(*status)
non-zero (true) if child exited normally

WEXITSTATUS(status)
8 least significant bits of status. This is the value the child passed to the exit() call or the return value of main().

 

Fork and pipe example code:

The following simple quick 'n dirty example illustrates forking and the use of the pipe system call. The code was mentioned in the tutorial and may be helpful for the assignment.

The parent process forks off a child then creates a pipe to the child and sends it characters it reads from STDIN (the standard input) the child then reverses the case of all characters it sees e.g 'a'->'A' and 'A'->'a' and prints the result.

Notice that it is important to close the 'ends' of the pipe that are not needed in both the parent and the child.

NOTE: Your code should close all file descriptors before exiting and check the return value of all system calls. This simple example doesn't do that in some places.

See the code here: pipex.c

Send any questions/comments to your TA (nadim).