0% found this document useful (0 votes)
9 views2 pages

Program 3 For Os

The document contains three C programs demonstrating the use of the fork() system call. The first program creates a child process and displays their PIDs, the second replaces the current process with a new one using exec() to run the 'ls' command, and the third generates Fibonacci numbers in child processes for a specified number of terms. Each program includes error handling for the fork() system call.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views2 pages

Program 3 For Os

The document contains three C programs demonstrating the use of the fork() system call. The first program creates a child process and displays their PIDs, the second replaces the current process with a new one using exec() to run the 'ls' command, and the third generates Fibonacci numbers in child processes for a specified number of terms. Each program includes error handling for the fork() system call.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

3.

1.Write a program to create process by using fork() system call


#include <stdio.h>
#include <unistd.h>
#include<sys/types.h>
int main() {
pid_t pid;

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;
}

You might also like