Assignment solution of cs604
Assignment solution of cs604
Question no.01:
Solution: (Part 1)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int factorial(int n) {
if (n <= 1) return 1;
int main() {
pid_t pid;
int i;
pid = fork();
if (pid == 0) {
// Child process
exit(0);
perror("Fork failed");
exit(1);
wait(NULL);
return 0;
Output:
Solution: (Part B) (step 01 Base version (no execlp)
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid1 = fork();
if (pid1 == 0) {
printf("Child 1: Exiting...\n");
exit(0);
pid2 = fork();
if (pid2 == 0) {
printf("Child 2: Exiting...\n");
exit(0);
wait(NULL);
wait(NULL);
return 0;
Output:
Solution: (Part B) (step 02 Modified version using execlp())
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid1 = fork();
if (pid1 == 0) {
perror("execlp failed");
exit(1);
pid2 = fork();
if (pid2 == 0) {
printf("Child 2: Exiting...\n");
exit(0);
}
// No wait() here
sleep(10); // Allows you to run `ps` in another terminal to check zombie state
return 0;
Output: