Ex02-Linux Process API-fork(), wait(), exec()
Operating systems Lab exercise
To write C Program that uses Linux Process API - fork(), wait(), exec()
Navigate to any Linux environment installed on the system or installed inside a virtual environment like virtual box/vmware or online linux JSLinux (https://bellard.org/jslinux/vm.html?url=alpine-x86.cfg&mem=192) or docker.
Write the C Program using Linux Process API - fork(), wait(), exec()
Test the C Program for the desired output.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{ //variable to store calling function's process id
pid_t process_id;
//variable to store parent function's process id
pid_t p_process_id;
//getpid() - will return process id of calling function
process_id = getpid();
//getppid() - will return process id of parent function
p_process_id = getppid();
//printing the process ids
//printing the process ids
printf("The process id: %d\n",process_id);
printf("The process id of parent function: %d\n",p_process_id);
return 0; }
##OUTPUT
./pidcheck.o
The process id: 56987
The process id of parent function: 55171
$ ps
PID TTY TIME CMD
55171 pts/0 00:00:00 bash
56991 pts/0 00:00:00 ps
#include <stdio.h>
#include<stdlib.h>
int main()
{ int pid;
pid=fork();
if(pid == 0)
{ printf("Iam child my pid is %d\n",getpid());
printf("My parent pid is:%d\n",getppid());
exit(0); }
else{
printf("I am parent, my pid is %d\n",getpid());
sleep(100);
exit(0);}
}
##OUTPUT
./forkcheck
I am parent, my pid is 57182
Iam child my pid is 57183
My parent pid is:57182
#include<stdio.h>
#include<unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
int main()
{ int status;
printf("Running ps with execlp\n");
execl("ps", "ps", "ax", NULL);
wait(&status);
if (WIFEXITED(status))
printf("child exited with status of %d\n", WEXITSTATUS(status));
else
puts("child did not exit successfully\n");
printf("Done.\n");
printf("Running ps with execlp. Now with path specified\n");
execl("/bin/ps", "ps", "ax", NULL);
wait(&status);
if (WIFEXITED(status))
printf("child exited with status of %d\n", WEXITSTATUS(status));
else
puts("child did not exit successfully\n");
printf("Done.\n");
exit(0);
}
##OUTPUT
The programs are executed successfully.