WRITE PROGRAMS USING THE FOLLOWING SYSTEM CALLS OFUNIX OPERATING SYSTEM: Fork, exec, getpid, exit, wait, close, stat, opendir, readdir.FORK & GETPIDAim : To Create a process in the following hierarchyParentChild1Child2Child3Algorithm 1.Declare the necessary variables.2.Parent process is the process of the program which is running.3.Create the child1 process using fork() When parent is active.4.Create the child2 process using fork() when child1 is active.5.Create the child3 process using fork() when child2 is active.Program //process1.c#include<stdio.h>void main(){int pid1,pid2,pid3;printf("Parent id is %d and root id is %d\n",getpid(),getppid());pid1=fork();if(pid1==0){printf("Process 1 id is %d and its parent id is %d\n",getpid(),getppid());pid2=fork();}if(pid2==0){printf("Process 2 id is %d and its parent id is %d\n",getpid(),getppid());pid3=fork();}if(pid1==0&&pid2==0&&pid3==0)CS2257- OS LabP a g e | 1

{printf("Process 3 id is %d and its parent id is %d\n",getpid(),getppid());}}Sample Output $ cc process1.c$ a.outParent id is 3553 and root id is 2495Process 1 id is 3554 and its parent id is 3553Process 2 id is 3555 and its parent id is 3554Process 3 id is 3556 and its parent id is 3555EXEClProgram //program1.c#include<stdio.h>#include<sys/types.h>#include<unistd.h>void main(){int pid1;pid1=fork();if(pid1==0){printf("Process id is %d ",getpid());printf("and its parent id is %d”,getppid());execl("/bin/who","who",0);}}Sample Output $ cc program2.c$ a.outProcess id is 3553 and parent id is 2495Rootttyp2jun2503.30sitttyp1jun2503.30OPENDIR & READDIRAim:To write a C program to display the files in the given directory Algorithm:1.Start the program2.Declare the variable to the structure dirent (defines the file system-independentdirectory) and also for DIRCS2257- OS LabP a g e | 2

3.Specify the directory path to be displayed using the opendir system call4.Check for the existence of the directory and read the contents of the directory usingreaddir system call (returns a pointer to the next active directory entry)5.Repeat the above step until all the files in the directory are listed6.Stop the programProgram#include<stdio.h>#include<dirent.h>main(){DIR *p;struct dirent *dp;p=opendir("."); //p=opendir("./shantha");if(p==NULL){perror("opendir");exit(0);}dp=readdir(p);while(p!=NULL){printf("%d%s\n",dp->d_ino,dp->d_name);dp=readdir(p);}}Output:"di.c" [New] 21L, 239C written[test1@localhost test1]$ cc di.c[test1@localhost test1]$ ./a.out1049278.442373..1049279.kde1049364.aa.c.swp1049285.balan.sh.swp1049387ar.sh1049404firstfit.c1049403wai.c1049406sta1.c1049405di.cRESULT: CS2257- OS LabP a g e | 3

0 Comments