2 | P a g e
Experiment No: 1 Write programs using the following system calls of UNIX operating
system: fork, exec, getpid, exit, wait, close, stat, opendir, readdir
AIM: Write programs using the following system calls of UNIX operating system:
fork, exec, getpid, exit, wait, close, stat, opendir, readdir
PROCEDURE:
a) fork(): Existing process can start a new process using fork() system call. It takes no arguments.
• If fork() returns a negative value, the creation of a child process was unsuccessful.
• If the child process is created successfully,
Once the child process has been created, then both the parent and child continue execution from
inside the fork() call. This means that the next action for both processes is to return from fork() with
its return value.
o fork() returns a zero to the child process.
o fork() returns the process ID of the child process, to the parent as shown below
The prototype for the fork() system call
#inciude <unistd.h>
pid_t fork(void);
b) getpid() system call: A process can use function getpid() to retrieve the process ID assigned to this
process.
c) exec() system call:
When you use the shell to run a command (ls, say) then at some point the shell will execute a fork() call to
get a new process running. Having done that, how does the shell then get ls to run in the child process instead
of the duplicate copy of the shell, which is what will be running immediately after the fork() call?
The solution in this case is to use an exec() system call. The simplest version of exec(). The prototype of
execv() system call is
int execv(pathname, argv);
The prototype for execv() shows that it only takes two parameters, the first is the full pathname to the
command to execute and the second is the argv value you want to pass into the new program.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Declare the variables pid,pid1,pid2.
STEP 3: Call fork() system call to create process.