CS604 Assignment 1 (Noshaba Nadeem)
CS604 Assignment 1 (Noshaba Nadeem)
Noshaba Nadeem
Bc230424161
Solution (a):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int factorial(int n) {
if (n == 0 || n == 1) return 1;
return n * factorial(n - 1);
}
int main() {
pid_t child_pid;
int status;
if (child_pid == -1) {
perror("fork failed");
exit(1);
}
if (child_pid == 0) {
printf("Child %d: PID = %d, PPID = %d\n", i+1, getpid(), getppid());
int num = i + 4;
int result = factorial(num);
exit(0);
}
}
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
pid_t child1, child2;
int status;
child1 = fork();
if (child1 == -1) {
perror("First fork failed");
exit(1);
}
if (child1 == 0) {
printf("First child: PID = %d, PPID = %d\n", getpid(), getppid());
printf("First child exiting\n");
exit(0);
}
child2 = fork();
if (child2 == -1) {
perror("Second fork failed");
exit(1);
}
if (child2 == 0) {
printf("Second child: PID = %d, PPID = %d\n", getpid(), getppid());
printf("Second child exiting\n");
exit(0);
}
int main() {
pid_t child1, child2;
if (child1 < 0) {
perror("First fork failed");
exit(1);
}
if (child1 == 0) {
// In first child process
printf("First child: PID = %d, PPID = %d\n", getpid(), getppid());
printf("First child executing 'ls -l'\n");
if (execlp("ls", "ls", "-l", NULL) == -1) {
perror("execlp failed in first child");
exit(1);
}
}
if (child2 < 0) {
perror("Second fork failed");
exit(1);
}
if (child2 == 0) {
// In second child process
printf("Second child: PID = %d, PPID = %d\n", getpid(), getppid());
printf("Second child exiting\n");
exit(0);
}
// Parent process
printf("Parent process: PID = %d\n", getpid());
printf("Parent sleeping for 15 seconds...\n");
printf("Open another terminal and run: ps -elf | grep defunct\n");
sleep(15);
return 0;
}