Write a c/c++ program that forks four processes from the same parent. The first
ID: 3744610 • Letter: W
Question
Write a c/c++ program that forks four processes from the same parent. The first process should find the prime numbers in the range 2-1000 and save them in a file named primes_2_1000.txt. The first process should find the prime numbers in the range 1001-2000 and save them in a file named primes_1001_2000.txt. The first process should find the prime numbers in the range 2001-3000 and save them in a file named primes_2001_3000.txt. The first process should find the prime numbers in the range 3001-4000 and save them in a file named primes_3001_4000.txt.The parent process should wait for the children to terminate.
Explanation / Answer
#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
void fun1(){
int i = 2;
FILE *fp;
fp = fopen("primes_2_1000.txt","w");
if(fp == NULL){
return;
}
int st = 0,j;
for(;i<=1000;i++){
st = 0;
for(j = i-1;j > 1;j--){
if(i%j == 0){
st = 1;
break;
}
}
if(st == 0){
fprintf(fp,"%d ",i);
}
}
fclose(fp);
}
void fun2(){
int i = 1001;
FILE *fp;
fp = fopen("primes_1001_2000.txt","w");
if(fp == NULL){
return;
}
int st = 0,j;
for(;i<=2000;i++){
st = 0;
for(j = i-1;j > 1;j--){
if(i%j == 0){
st = 1;
break;
}
}
if(st == 0){
fprintf(fp,"%d ",i);
}
}
fclose(fp);
}
void fun3(){
int i = 2001;
FILE *fp;
fp = fopen("primes_2001_3000.txt","w");
if(fp == NULL){
return;
}
int st = 0,j;
for(;i<=3000;i++){
st = 0;
for(j = i-1;j > 1;j--){
if(i%j == 0){
st = 1;
break;
}
}
if(st == 0){
fprintf(fp,"%d ",i);
}
}
fclose(fp);
}
void fun4(){
int i = 3001;
FILE *fp;
fp = fopen("primes_3001_4000.txt","w");
if(fp == NULL){
return;
}
int st = 0,j;
for(;i<=4000;i++){
st = 0;
for(j = i-1;j > 1;j--){
if(i%j == 0){
st = 1;
break;
}
}
if(st == 0){
fprintf(fp,"%d ",i);
}
}
fclose(fp);
}
int main()
{
int pid[4];
int status[4];
pid[0] = fork();
if(pid[0] == 0){
fun1();
}
pid[1] = fork();
if(pid[1] == 0){
fun2();
}
pid[2] = fork();
if(pid[2] == 0){
fun3();
}
pid[3] = fork();
if(pid[3] == 0){
fun4();
}
int i;
for(i = 0;i<4;i++){
waitpid(pid[i],&status[i],0);
}
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.