Program 3 For Os
Program 3 For Os
pid = fork();
if (pid == -1) {
perror("Fork failed");
return 1;
}
if (pid == 0) {
printf("Child process: PID = %d, Parent PID = %d\n", getpid(), getppid());
} else {
printf("Parent process: PID = %d, Child PID = %d\n", getpid(), pid);
}
return 0;
}
2.write a program for the current process is overwritten by a new process using fork() and
exec() system calls.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include<sys/wait.h>
int main() {
pid_t pid;
pid = fork();
if (pid == -1) {
perror("Fork failed");
exit(1);
}
if (pid == 0) {
printf("Child process: Executing `ls` command\n");
execl("/bin/ls", "ls", "-l", NULL);
perror("Exec failed");
exit(1);
} else {
printf("Parent process: Waiting for child to finish\n");
wait(NULL);
printf("Parent process: Child finished\n");
}
return 0;
}
3.Write a program to find Fibonacci series of the given number by using fork () system call.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int fibonacci(int n) {
if (n <= 1) {
return n;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
int main() {
int n;
printf("Enter the number of terms in Fibonacci sequence: ");
scanf("%d", &n);
for (int i = 0; i < n; i++) {
pid_t pid = fork();
if (pid < 0) {
perror("Fork failed");
exit(1);
}
if (pid == 0) {
printf("Child Process (PID: %d) - Fibonacci of %d is %d\n", getpid(), i, fibonacci(i));
exit(0);
} else {
wait(NULL);
}
}
return 0;
}