Lab09: Coding in C (Fork System Call) Objectives
Lab09: Coding in C (Fork System Call) Objectives
Lab09: Coding in C (Fork System Call) Objectives
Objectives
To learn how to execute and use a system call
1. C language
The C programming language is an excellent choice for beginning programmers as well as for people
who do not intend to become a programmer but just want the experience of creating a program.
This is because it is relatively simple, yet powerful and widely used. It is also because C is the basis
for many other programming languages, and thus experience gained with C can be applied to those
languages as well. In addition, experience with C is useful for obtaining an in-depth understanding
of Linux and other Unix-like operating systems, because they are largely written in C.
Every C program has exactly one function named main(). A function is a set of one or
more statements that are enclosed in curly brackets, perform some operation and return a single
value to the program in which they reside; it could also be looked at as a subprogram. The main()
function is the starting point of any program; that is, it is where the program begins execution (i.e.,
running); any other functions are subsequently executed.
Example code:
#include <stdio.h>
/* This is a comment */
int main()
{
printf("Hello, world!\n");
return 0;
}
Compilation and execution
$ ./hello
2. System call
System calls acts as entry point to OS kernel. There are certain tasks that can only be done if a
process is running in kernel mode. Examples of these tasks can be interacting with hardware etc. So
if a process wants to do such kind of task then it would require itself to be running in kernel mode
which is made possible by system calls.
BU,CS DEPARTMENT LAB-09
Implementation
BU,CS DEPARTMENT LAB-09
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is
returned in the child’s thread of execution. On failure, a -1 will be returned in the parent’s context, no
child process will be created, and errno will be set appropriately.
Definition:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
main() {
char *temp1,*temp2;
temp1="Hello";
temp2="world";
execlp("echo","echo",temp1,temp2,NULL);
printf("Error");
int main()
{
pid_t childpid; /* variable to store the child's pid */
int retval; /* child process: user-provided return code */
int status; /* parent process: child's exit status */
/* only 1 int variable is needed because each process would have its
own instance of the variable
here, 2 int variables are used for clarity */
EXERCISES
Exercises