Lab Report 3 - OS
Lab Report 3 - OS
ID: ITITIU20244
LAB REPORT 3
This session aims at revising multiple processes programming on Linux. The focus is on
implement-
ing programs to do some particular tasks using system calls.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if(pid < 0) {
perror("fork: Cannot create new process");
exit(1);
} else if (pid == 0) {
printf("Child process created! %d\n", getpid());
} else {
printf("Parent process created! %d\n", getpid());
}
return 0;
}
Output:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
pid_t waitpid(pid_t pid, int *status, int options);
int main() {
pid_t pid = fork();
if(pid < 0) {
perror("fork: Cannot create new process");
exit(1);
} else if (pid == 0) {
printf("Child process created! %d\n", getpid());
} else {
printf("Parent process created! %d\n", getpid());
waitpid(pid, NULL, 0);
}
return 0;
}
Screenshot:
Explain:
Wait for the child process. The child process will become an orphan
process, if the parent process is terminated.
● Execute a file
● Code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
perror("fork: cannot create a new process");
exit(EXIT_FAILURE);
} else if (pid == 0) {
/* Child process code */
printf("Child process ID: %d\n", getpid());
if (WIFEXITED(status)) {
printf("Child process exited with status %d\n",
WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Child process terminated by signal %d\n",
WTERMSIG(status));
}
}
return 0;
}
● Screenshot
Problem 2.2: Multi-process Growing program
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdbool.h>
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
verifyNumber(num, getpid());
exit(EXIT_SUCCESS);
}
}
return 0;
}
Screenshot:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/wait.h>
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
verifyPrime(num, getpid());
exit(EXIT_SUCCESS);
}
}
return 0;
}
Screenshot:
Problem 2.2: Multi-process Fibonacci program
Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdbool.h>
#include <math.h>
#include <sys/types.h>
#include <sys/wait.h>
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// Child process
verifyFibonacci(num, getpid());
exit(EXIT_SUCCESS);
}
}
return 0;
}
Screenshot: