Professional Documents
Culture Documents
Operating System II: Abdullah Ahmed
Operating System II: Abdullah Ahmed
Operating System II
Lab 4
.
BY:
ABDULLAH AHMED
COMPUTER.ENG
Write and execute a C program using fork system call to do the followings:
The parent process will create a child process and waits until the child process finish. The
parent will print "we are done" at the end.
The child process will ask the user to enter two numbers and prints the result on the screen.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main() {
int pid = fork();
if (pid == 0) {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
printf("Sum = %d\n", num1 + num2);
} else {
wait(NULL);
printf("Child process completed.\n");
}
return 0;
}
Write number into file
#include <stdio.h>
#include <stdlib.h>
int main() {
int num;
FILE *fptr;
fptr = fopen("program.txt", "w");
if (fptr == NULL) {
printf("Error opening file.\n");
return 1;
}
printf("Enter the number: ");
scanf("%d", &num);
fprintf(fptr, "%d", num);
fclose(fptr);
return 0;
}
Read from the file
#include <stdio.h>
#include <stdlib.h>
int main() {
int num;
FILE *fptr;
if (fptr == NULL) {
return 1;
printf("%d\n", num);
fclose(fptr);
return 0;
}
The
End