Lab#7 OS
Lab#7 OS
Lab7
Task#1
Code:
#include<stdio.h>
#include<unistd.h>
int main()
return 0;
Output:
Task#2
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int pid = fork();
// child process because return value is zero
if (pid == 0) {
printf("This is the child process. My pid is %d and my parent's id is %d.\n", getpid(), getppid());
}
// Parent process because return value is non-zero
else {
printf("This is the parent process. My pid is %d and my parent's id is %d.\n", getpid(), pid);
}
return 0;
}
Output:
Task#4
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t forkStatus;
forkStatus = fork();
/* Child... */
if (forkStatus == 0) {
printf("Child is running, processing.\n");
execl("/bin/ls", "ls", "-l", (char *) 0);
sleep(5);
printf("Child is done, exiting.\n");
/* Parent... */
} else if (forkStatus != -1) {
printf("Parent is waiting...\n");
wait(NULL);
printf("Parent is exiting...\n");
} else {
perror("Error while calling the fork function");
}
return 0;
}
Output:
Task#6
Code:
// Child becomes Zombie as parent is sleeping
// when child process exits.
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
// Fork returns process id
// in parent process
pid_t child_pid = fork();
// Parent process
if (child_pid > 0){
printf("Parent will sleep");
sleep(50);
}
// Child process
else
exit(0);
return 0;
}
Output: