Dev 6
Dev 6
Practical: 6
1. Create a chain of processes where one parent has exactly one child as per
sample chaingiven by the Instructor. Sequence:1
PROCESS 0 --> PROCESS 1 --> PROCESS 2 --> PROCESS 3 -->
PROCESS 4--> PROCESS 5 --> PROCESS 6
Display PIDs of all processes.
#include <stdio.h>
#include <unistd.h>
int main() {
int levels = 6;
pid_t pid;
printf("PROCESS 0 (PID: %d)\n", getpid());
for (int i = 1; i <= levels; i++) {
pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
printf("--> ");
printf("PROCESS %d (PID: %d)", i, getpid());
} else {
break;
}
}
printf("\n");
return 0;
}
2. Jack want to sort out coins of various values as per below input. Design
programtosort the coins in the parent process and print the reversely sorted
coins in the child process. For example:
Input : 10, 5, 1, 20, 2
Output :
Parent process:
Sorted coins are : 1, 2, 5, 10, 20
Child process
Reversely sorted coins are: 20, 10,5,2,1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int compare(const void *a, const void *b) {
return (*(int*)b - *(int*)a);
}
int main() {
int coins[] = {10, 5, 1, 20, 2};
int num_coins = sizeof(coins) / sizeof(coins[0]);
int sorted_coins[num_coins];
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
return 1;
} else if (pid == 0) {
printf("Child process --> ");
printf("Reversely sorted coins are: ");
for (int i = 0; i < num_coins; i++) {
printf("%d", sorted_coins[i]);
if (i != num_coins - 1) {
printf(", ");
}
}
printf("\n");
} else {
printf("Parent process --> ");
printf("Sorted coins are: ");
for (int i = 0; i < num_coins; i++) {
sorted_coins[i] = coins[i];
}
qsort(sorted_coins, num_coins, sizeof(int), compare);
for (int i = 0; i < num_coins; i++) {
printf("%d", sorted_coins[i]);
if (i != num_coins - 1) {
printf(", ");
}
}
printf("\n");
wait(NULL);
}
return 0;
}