Unix System Calls-1
Unix System Calls-1
Objective
To write a programs using the following system calls of UNIX operating system:
fork, exec, getpid, exit, wait, close, stat, opendir, readdir
Description
When a computer is turned on, the program that gets executed first is called the ``operating
system.'' It controls pretty much all activity in the computer. This includes who logs in, how disks
are used, how memory is used, how the CPU is used, and how you talk with other computers.
The operating system we use is called "Unix".
The way that programs talk to the operating system is via ``system calls.'' A system call looks
like a procedure call (see below), but it's different -- it is a request to the operating system to
perform some activity.
Getpid
Each process is identified by a unique process id (called a “pid”). The init process (which is the
supreme parent to all processes) posesses id 1. All other processes have some other (possibly
arbitrary) process id. The getpid system call returns the current process’ id as an integer.
// …
int pid = getpid();
printf(“This process’ id is %d\n“,pid);// …
fork
The fork system call creates a new child process. Actually, it’s more accurate to say that it forks
a currently running process. That is, it creates a copy of the current process as a new child
process, and then both processes resume execution from the fork() call. Since it creates two
processes, fork also returns two values; one to each process. To the parent process, fork returns
the process id of the newly created child process. To the child process, fork returns 0. The reason
it returns 0 is precisely because this is an invalid process id. You would have no way of
differentiating between the parent and child processes if fork returned an arbitrary positive
integer to each.
Therefore, a typical call to fork looks something like this:
int pid;
if ( (pid = fork()) == 0 ) {
/* child process executes inside here */
}
else {
/* parent process executes inside here */
}