0% found this document useful (0 votes)
141 views27 pages

Familiarity and Usage of System Calls of LINUX / WINDOWS-NT On Process Management

The document describes using the wait() system call to synchronize the execution of parent and child processes. It discusses how wait() causes the parent process to suspend execution until a child process exits or a signal is received. The algorithm creates a child process using fork(), and the parent process uses wait() to block until the child terminates, at which point it resumes and prints the child's exit status. A C program example demonstrates creating a child process, the parent waiting on the child, and printing status information.

Uploaded by

david_nelaturi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
141 views27 pages

Familiarity and Usage of System Calls of LINUX / WINDOWS-NT On Process Management

The document describes using the wait() system call to synchronize the execution of parent and child processes. It discusses how wait() causes the parent process to suspend execution until a child process exits or a signal is received. The algorithm creates a child process using fork(), and the parent process uses wait() to block until the child terminates, at which point it resumes and prints the child's exit status. A C program example demonstrates creating a child process, the parent waiting on the child, and printing status information.

Uploaded by

david_nelaturi
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 27

Familiarity and usage of system calls of LINUX / WINDOWS-NT on Process

management
Experiment # 16: Program to Illustrate Fork() System Call
AIM: To write a program in to illustrate the usage of fork system call

THEORY:

System call fork() is used to create processes. It takes no arguments and returns a process ID.
The purpose of fork() is to create a new process, which becomes the child process of the caller.
After a new child process is created, both processes will execute the next instruction following
the fork() system call. Therefore, we have to distinguish the parent from the child. This can be
done by testing the returned value of fork():

• If fork() returns a negative value, the creation of a child process was unsuccessful.
• fork() returns a zero to the newly created child process.
• fork() returns a positive value, the process ID of the child process, to the parent. The
returned process ID is of type pid_t defined in sys/types.h.

If the call to fork() is executed successfully, Unix will

• Make two identical copies of address spaces, one for the parent and the other for the
child.
• Both processes will start their execution at the next statement following the fork() call.
• Since both processes have identical but separate address spaces, those variables
initialized before the fork() call have the same values in both address spaces.

When the main program executes fork(), an identical copy of its address space, including the
program and all data, is created. System call fork() returns the child process ID to the parent and
returns 0 to the child process. The following figure shows that in both address spaces there is a
variable pid. The one in the parent receives the child's process ID 27421 and the one in the child
receives 0.

• In the parent, since pid is non-zero, Parent Process gets executed. On the other hand,
the child has a zero pid and Child Process gets executed
REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

ALGORITHM :
STEP 1:Get the process id of process and store it in id using getpid() system call
STEP 2: Fork the process and assign the return value of fork to childid
STEP 3: If the childid is greater than ‘0’ then
Print process id of parent process.
STEP 4: Else print process id of child process

Diagram illustrating the Fork System Call


PROGRAM:
#include <stdio.h> /* printf, stderr, fprintf */
#include<sys/types.h>/*pid_t Used for process IDs and process group IDs. */
main()
{
int id,childid;
id=getpid();
if(childid=fork()>0)
{
printf("\n i am in the parent process %d",id);
printf("\n i am in the parent process %d",getpid());
printf("\n i am in the parent process %d\n",getppid());
}
else
{
printf("\n i am in child process %d",id);
printf("\n i am in the child process %d",getpid());
printf("\n i am in the child process %d",getppid());
}
}

OUTPUT:
[david@vasavi-edu david]$ ./a.out
i am in child process 27421
i am in the child process 27422
i am in the child process 27421
i am in the parent process 27421
i am in the parent process 27421
[david@vasavi-edu david]$
Result: A program in c language to illustrate the usage of fork() system call is executed
successfully.
Familiarity and usage of system calls of LINUX / WINDOWS-NT on Process
management
Experiment # 17: To Demonstrate The Usage Of Execv( ) System Call

AIM: To write a program to illustrate the “Execv()” System call

THEORY :
The exec family of functions provides a facility for overlaying the process image of the
calling process with a new image.
int execv( const char *path, char *const argv[])
The execv function takes exactly two parameters, a pathname for the executable file and
an argument array.
It is similar to execl() and also allows the flexibility of passing as arguments
1. A process is created
2. Array of characters are explicitly defined and are passed as arguments to
execv()
3. The array ‘arg’ includes object code file, “-l” for long listing of files and character
termination
4. These arguments are passed as arg to execv() in addition to path of object code file

REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

ALGORITHM:
STEP 1: Initialize the character pointer array with the command line arguments.
STEP 2: Invoke the execv function by passing the pathname of the file to be executed
and the command line argument array
STEP 3: Terminate the program
PROGRAM:

#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>
main()
{
char *arg[]={"ps","-l",(char*)0};
printf("before execv");
execv("/bin/ps",arg);
}

OUTPUT:

[david@vasavi-edu david]$ ./a.out


F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
100 S 518 9723 28078 0 74 0 - 626 wait4 pts/1 00:00:00 bash
000 R 518 25326 9723 0 78 0 - 764 - pts/1 00:00:00 ps
[david@vasavi-edu david]$

Result: A program in c language to illustrate the usage of Execv() system call is executed
successfully.
Familiarity and usage of system calls of LINUX / WINDOWS-NT on Process
management
Experiment # 18 : To Demonstrate The Usage Of Execl( ) System Call
AIM: To write a program to demonstrate the Usage Of Execl( ) System Call
THEORY :

It is used to replace the currently running process with a new process image.
This is similar to Execv system call.
int execl( const char *path, const char *arg, ...)
A processs is created
1) Path of the object file and command line arguments terminated by null value is
passed as arguments of the function.
2) Since the command “ls” is used, it displays the file names in that directory

REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

ALGORITHM :

STEP 1: Print the message ‘Before execl’


STEP 2:Invoke the execl function by passing the pathname of the file to be executed
and the command line arguments.
STEP 3: Print the message ‘After execl’.
STEP 4: Terminate the program
PROGRAM:

#include<sys/types.h>
#include<unistd.h>
#include<stdio.h>

main()
{
printf(“Before Execl \n”);
execl(“/bin/ls”,”ls”,(char*)0);
printf(“After Execl\n”);
}

OUTPUT:
[david@vasavi-edu david]$ ./a.out
Before Execl
a a2.c a3.c a4.o a6.o a.out echo_it1 numbers temp
a1.c a2.o a3.o a5.c a.c a.sh ex1 os-lab
a1.sh a2.sh a4.c a6.c a.o ece.c names stats
[david@vasavi-edu david]$

Result: A program in c language to illustrate the usage of Execl() system call is executed
successfully.
Familiarity and usage of system calls of LINUX / WINDOWS-NT on Process
management
Experiment #19 To Synchronize The Execution Of Parent And Child Process Using Wait( )
System Call
AIM: To write a program to Synchronize the Execution of Parent and Child Process Using
Wait ( ) System Call.

THEORY :
To show synchronization between parent and child process wait system call is used.
This function blocks the calling process until one of its child processes exits or a signal is
received.

wait() takes the address of an integer variable and returns the process ID of the completed
process. Some flags that indicate the completion status of the child process are passed back
with the integer pointer. One of the main purposes of wait() is to wait for completion of child
processes.

The execution of wait() could have two possible situations.

1. If there are at least one child processes running when the call to wait() is made,
the caller will be blocked until one of its child processes exits. At that moment, the
caller resumes its execution.
2. If there is no child process running when the call to wait() is made, then this
wait() has no effect at all. That is, it is as if no wait() is there.

pid_t wait (int *stat) – This function causes the caller to suspend execution until a
child’s status becomes available or until the caller receives a signal.

1) The parent process creates a child process and waits till the child is executed and
terminates. Then parent process is resumed.
2) The exit status of the child process is passed to the parent process through wait
system call.

REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

ALGORITHM :

STEP 1: Create a child process using fork system call.


STEP 2: If the return value of the fork is –1 then display the error message and terminate
the program.
STEP 3: If the return value of fork is 0, then display the child process id and terminate it
using exit function by specifying the status.
STEP 4: If the return value is +ve, then display the parent process information and
invoke the wait system call to block parent process until the child terminates.
STEP 5: When the child process terminates, then the parent process is resumed and
terminated after displaying the exit status of the child process.
PROGRAM :

#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

main()
{
pid_t pid;
int rv;

switch(pid=fork())
{
case -1:
perror("fork");
exit(1);
case 0:
printf("\n CHILD: This is the child process!\n");
fflush(stdout);
printf("\n CHILD: My PID is %d\n", getpid());
printf("\n CHILD: My parent's PID is %d\n",getppid());
printf("\n CHILD: Enter my exit status (make it small):\n ");
printf("\n CHILD: I'm outta here!\n");
scanf(" %d", &rv);
exit(rv);
default:
printf("\nPARENT: This is the parent process!\n");
printf("\nPARENT: My PID is %d\n", getpid());
wait(&rv);
printf("\nPARENT: My child's PID is %d\n", pid);
printf("\nPARENT: I'm now waiting for my child to exit()...\n");
printf("\nPARENT: My child's exit status is:
%d\n",WEXITSTATUS(rv));
printf("\nPARENT: I'm outta here!\n");
}
}

OUTPUT:

[david@vasavi-edu david]$ ./a.out


CHILD: This is the child process!
CHILD: My PID is 4584
CHILD: My parent's PID is 4583
CHILD: Enter my exit status (make it small):
CHILD: I'm outta here!
PARENT: This is the parent process!
PARENT: My PID is 4583
3
PARENT: My child's PID is 4584
PARENT: I'm now waiting for my child to exit()...
PARENT: My child's exit status is: 3
PARENT: I'm outta here!
[david@vasavi-edu david]$

Result: A program in c to Synchronize the Execution of Parent and Child Process Using
Wait ( ) System Call.
Familiarity and usage of system calls of LINUX / WINDOWS-NT on Process
management
Experiment # 20: Use Of Creat And Open System Calls

AIM: To write a program in C to Illustrate the use of create and open system calls using
command line arguments.

REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

THEORY :
To explicitly open files in order to read or write them. There are two system calls for this,
open and creat

open is rather like the fopen, except that instead of returning a file pointer, it returns a
file descriptor, which is just an int. open returns -1 if any error occurs.
int open(const char *path,int mode,int accessp)
The path parameter points to the pathname of the file and the mode parameter specifies
the access modes. The third parameter specifies the access permissions if file is being
created.
The creat system call is used to create a new file.
int creat(const char *pathname,int accessp)
The path parameter includes the pathname of the file and the parameter accessp specifies
the access permissions of the file to be created.

Access Modes Access Permissions

O_RDONLY open for reading only

O_WRONLY open for writing only

O_RDWR open for both reading and writing


In computer programming, a file descriptor is an abstract indicator for accessing a file. The term
is generally used in POSIX operating systems. A file descriptor is an index for an entry in a
kernel-resident data structure containing the details of all open files. In POSIX this data structure
is called a file descriptor table, and each process has its own file descriptor table. The user
application passes the abstract key to the kernel through a system call, and the kernel will access
the file on behalf of the application, based on the key. The application itself cannot read or write
the file descriptor table directly.

In Unix-like systems, file descriptors can refer to files, directories, block or character devices
(also called "special files"), sockets, FIFOs (also called named pipes), or unnamed pipes.

The FILE * file handle in the C standard I/O library routines is technically a pointer to a data
structure managed by those library routines; one of those structures usually includes an actual
low level file descriptor for the object in question on Unix-like systems. Since file handle refers
to this additional layer, it is not interchangeable with file descriptor.

ALGORITHM:

STEP 1: Open the first file in read only mode and read the data from the file.
STEP 2: Create the second file using the creat system call and open this newly created
file in write only mode.
STEP 3: Write the data to the second file that has been read from the first file.
STEP 4: Close the files and terminate the program.
PROGRAM :

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
main(int argc,char *argv[])
{
int fid1,fid2,i;
char buff[500];
if(argc!=3)
{
printf("error");
exit(1);
}
fid1=open(argv[1],0);
i=read(fid1,buff,500);
creat(argv[2],S_IRWXU);
fid2=open(argv[2],1);
write(fid2,buff,i);
close(fid1);
close(fid2);
}
OUTPUT:

[david@vasavi-edu david]$ ./a.out fd.c tem


[david@vasavi-edu david]$ cat tem
#include<sys/types.h>
main(int argc,char *argv[])
{
int fid1,fid2,i;
char buff[500];
if(argc!=3)
{
printf("error");
exit(1);
}
fid1=open(argv[1],0);
i=read(fid1,buff,500);
creat(argv[2],S_IRWXU);
fid2=open(argv[2],1);
write(fid2,buff,i);
close(fid1);
close(fid2);
}

[david@vasavi-edu david]$
Result: A program in C is executed to Illustrate the use of create and open system calls using
command line arguments.
Familiarity and usage of system calls of LINUX / WINDOWS-NT on Process
management

Experiment # 21 Illustrate the use of creat and open system calls

AIM: To write a program in C to Illustrate the use of open and create system calls without using
command line arguments
THEORY :
The open function associates a file descriptor with a file or physical device.
int open(const char *path,int mode,int accessp)
The path parameter points to the pathname of the file and the mode parameter specifies
the access modes. The third parameter specifies the access permissions if file is being
created.
The creat system call is used to create a new file.
int creat(const char *pathname,int accessp)
The path parameter includes the pathname of the file and the parameter accessp specifies
the access permissions of the file to be created.
The names of the files are included instead of argumens tin the system calls.
REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

ALGORITHM :

STEP 1: Open the first file in read only mode and read the data from the file.
STEP 2: Create the second file using the creat system call and open this newly created
file in write only mode.
STEP 3: Write the data to the second file that has been read from the first file.
STEP 4: Close the files and terminate the program.
PROGRAM:

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
main()
{
int fid1,fid2,i;
char buff[500];
fid1=open("test",0);
i=read(fid1,buff,100);
creat("sample",S_IRWXU);
fid2=open("sample",2);
write(fid2,buff,i);
close(fid1);
close(fid2);
}

OUTPUT:

[david@vasavi-edu david]$ ./a.out


[david@vasavi-edu david]$ cat sample
Hello how are you
[david@vasavi-edu david]$

Result: A program in C is executed to Illustrate the use of open and create system calls
without using command line arguments.
Familiarity and usage of system calls of LINUX / WINDOWS-NT on File management

Experiment # 22: Display Attributes Of A File Using Stat() Systemcall

AIM: To write a program in C to Display attributes of a given file using stat system call.

THEORY:
The stat function returns information about the specified file.
int stat(const char *file_name, struct stat *buf);
This function retrieves the status of the file pointed to by file_name and fills in buf.
It returns a stat structure, which contains the following fields:
struct stat {
dev_t st_dev; /* device */
ino_t st_ino; /* inode */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device type (if inode device) */
off_t st_size; /* total size, in bytes */
unsigned long st_blksize; /* blocksize for filesystem I/O */
unsigned long st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last change */
};

REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX
ALGORITHM :

STEP 1: Declare a variable of structure type stat.


STEP 2: Invoke the stat system call by passing filename and address of stat variable as
parameters of the function.
STEP 3: If stat function returns zero, then display the file attributes else display the error
message.

PROGRAM:

#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
int main(int argc,char *argv[])
{
if(argc!=2)
{
printf("wrong no: of arguments");
exit(1);
}
else
{
struct stat str;
stat(argv[1],&str);
printf("\nmode is %lu\n",str.st_mode);
printf("device type is %lu\n",str.st_dev);
printf("mode no: is %lu\n",str.st_ino);
printf("no: of inks is %lu\n",str.st_nlink);
printf("user id is %lu\n",str.st_uid);
printf("group id is %lu\n",str.st_gid);
printf("device name is %lu\n",str.st_rdev);
printf("block size is %lu\n",str.st_blksize);
printf("no: of blocks is %lu\n",str.st_blocks);
}
return(0);
}

OUTPUT:

[david@vasavi-edu david]$ ./a.out file.c


mode is 33204
device type is 2053
mode no: is 1454358
no: of inks is 1
user id is 4140
group id is 4141
device name is 34817
block size is 4096
no: of blocks is 8
[david@vasavi-edu david]$
Result: A program in C to Display attributes of a given file using stat system call is executed
successfully.
Implementing a program to get and set the environment variables using
system calls.
Experiment # 23 Display The List Of Environment Variables
AIM: To write a program in C to display the list of Environment variables.
THEORY :

The variable environ points to an array of strings called the `environment'. (This variable must be
declared in the user program, but is declared in the header file unistd.h in case the header files
came from libc4 or libc5, and in case they came from glibc and _GNU_SOURCE was defined.)
This array of strings is made available to the process by the exec call that started the process. By
convention these strings have the form `name=value'. Common examples are:

USER
The name of the logged-in user (used by some BSD-derived programs).
LOGNAME
The name of the logged-in user (used by some System-V derived programs).
HOME
A user's login directory, set by login from the password file passwd.
LANG
The name of a locale to use for locale categories when not overridden by LC_ALL or
more specific environment variables like LC_COLLATE, LC_CTYPE,
LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME, cf. locale.
PATH
The sequence of directory prefixes that sh and many other programs apply in searching
for a file known by an incomplete path name. The prefixes are separated by `:'. (Similarly
one has CDPATH used by some shells to find the target of a change directory command,
MANPATH used by man to find manual pages, etc.)
PWD
The current working directory. Set by some shells.
SHELL
The file name of the user's login shell.
TERM
The terminal type for which output is to be prepared.
PAGER
The user's preferred utility to display text files.
EDITOR/VISUAL
The user's preferred utility to edit text files.
BROWSER
The user's preferred utility to browse URLs. Sequence of colon-separated browser
commands.
ALGORITHM :

STEP 1: Declare environ as character type pointer to pointer variable.


STEP 2: Initialize the loop variable i to 0.
STEP 3: If the string in the environ array at index i is not null then print the string else
goto step 5.
STEP 4: Increment the value of i by 1 and goto step 3.
STEP 5: Terminate the program.

REQUIREMENTS:

HARDWARE : PIII Processor , 128 MB RAM, 10GB


SOFTWARE : OS: LINUX

PROGRAM:

#include<stdio.h>
main(int argc,char *argv[])
{
extern char **environ;
int i;
for(i=0;environ[i]!=(char *)0;i++)
printf("%s\n",environ[i]);
return;
}
OUTPUT:
[david@vasavi-edu david]$ ./a.out
PWD=/home/david
REMOTEHOST=135.135.5.23
HOSTNAME=vasavi-edu
LESSOPEN=|/usr/bin/lesspipe.sh %s
USER=david
LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;0
1:or=01;05;37;41:mi=01;05;37;41:ex=01;32:*.cmd=01;32:*.exe=01;32:*.com=01;32:*.b
tm=01;32:*.bat=01;32:*.sh=01;32:*.csh=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:
*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*
.bz=01;31:*.tz=01;31:*.rpm=01;31:*.cpio=01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;3
5:*.xbm=01;35:*.xpm=01;35:*.png=01;35:*.tif=01;35:
MACHTYPE=i386-redhat-linux-gnu
MAIL=/var/spool/mail/david
INPUTRC=/etc/inputrc
LANG=en_US
LOGNAME=david
SHLVL=1
SHELL=/bin/bash
HOSTTYPE=i386
OSTYPE=linux-gnu
HISTSIZE=1000
TERM=vt100
HOME=/home/david
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
PATH=/usr/local/bin:/bin:/usr/bin:/usr/X11R6/bin:/home/david/bin
_=./a.out
[david@vasavi-edu david]$
Result: A program in C to display the list of Environment variables is executed successfully.
Familiarity and usage of system calls of LINUX /WINDOWS-NT on IPC
& Synchronization – pipes

Experiment # 24 : To Send A Message From Process A To Process B By Using Pipe() System


Call
AIM : To write a C program to send a From Process A To Process B By Using Pipe() System
Call
THEORY :
• A Unix pipe provides a one-way flow of data.
• For example, if a Unix users issues the command
• who | sort | lpr

then the Unix shell would create three processes with two pipes between them:

• A pipe can be explicitly created in Unix using the pipe system call. Two file descriptors
are returned--fildes[0] and fildes[1], and they are both open for reading and writing. A
read from fildes[0] accesses the data written to fildes[1] on a first-in-first-out (FIFO)
basis and a read from fildes[1] accesses the data written to fildes[0] also on a FIFO basis.

• When a pipe is used in a Unix command line, the first process is assumed to be writing to
stdout and the second is assumed to be reading from stdin. So, it is common practice to
assign the pipe write device descriptor to stdout in the first process and assign the pipe
read device descriptor to stdin in the second process. This is elaborated below in the
discussion of multiple command pipelines.

A pipe is an object that can act like a file which can be written to and read from. We can
write bytes to the pipe. A pipe is useful when we want to write from one process and read
from another. So pipes are used as method of communication between processes, an
alternative to messages.
Pipe provides a one-way flow of data. A pipe is created by the pipe system call.
int pipe(int *filedes);
Two file descriptors are returned
filedes[0] which is open for reading
filedes[1] which is open for writing

REQUIREMENTS :

HARDWARE : PIII Processor , 128 MB RAM, 10GB

SOFTWARE : OS: LINUX

ALGORITHM :

STEP 1: Invoke pipe system call to get the return value


STEP 2: If the pipeid is less than 0 then
Print as unable to create the pipe
STEP 3: Read bytes from the keyboard into buffer
STEP 4: Write the number of bytes read into the pipe from the buffer
STEP 5: Read from the pipe into the buffer i number of bytes
STEP 6: Write the bytes onto the screen
PROGRAM:
#include<stdio.h>
main()
{
int pipeid[2],n;
char buff1[100],buff2[100];
if(pipe(pipeid)<0)
{
printf("unable to create pipe");
exit(1);
}
else
n=read(0,buff1,100);
write(pipeid[1],buff1,n);
read(pipeid[0],buff2,n);
write(1,buff2,n);
}

OUTPUT:

[vasavi-edu david]$cc pipe.c


[vasavi-edu david]$./a.out
Unix
Unix
[vasavi-edu david]$
Result: A program in c to send a From Process A To Process B By Using Pipe() System Call
is executed successfully.

You might also like