Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

2024

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;

fptr = fopen("program.txt", "r");

if (fptr == NULL) {

printf("Error opening file.\n");

return 1;

fscanf(fptr, "%d", &num);

printf("%d\n", num);

fclose(fptr);

return 0;

}
The
End

You might also like