2025-01-31 11:18:35 +05:30
|
|
|
// stdlib import
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
|
|
|
|
// bash utilities import
|
|
|
|
#include <sys/types.h>
|
|
|
|
#include <sys/wait.h>
|
|
|
|
#include <unistd.h>
|
|
|
|
|
|
|
|
void main () {
|
|
|
|
|
|
|
|
// array declaration
|
|
|
|
char *strings[5];
|
|
|
|
char *string_cpy[5];
|
|
|
|
char temp[100];
|
|
|
|
|
|
|
|
// variables reqd
|
|
|
|
int i,j;
|
|
|
|
pid_t pid;
|
|
|
|
int status;
|
|
|
|
|
|
|
|
// input
|
|
|
|
printf("Enter strings to print: \n");
|
2025-02-07 01:25:19 +05:30
|
|
|
const size_t str_size = 100;
|
2025-01-31 11:18:35 +05:30
|
|
|
for (i = 0; i < 5; i++) {
|
2025-02-07 01:25:19 +05:30
|
|
|
strings[i] = malloc(str_size);
|
|
|
|
string_cpy[i] = malloc(str_size);
|
|
|
|
if (!strings[i] || !string_cpy[i]) {
|
|
|
|
fprintf(stderr, "Memory allocation failed\n");
|
|
|
|
exit(1);
|
|
|
|
}
|
|
|
|
if (fgets(strings[i], str_size, stdin)) {
|
|
|
|
memcpy(string_cpy[i], strings[i], str_size);
|
|
|
|
}
|
2025-01-31 11:18:35 +05:30
|
|
|
}
|
|
|
|
|
|
|
|
// forking
|
|
|
|
pid = fork();
|
|
|
|
|
|
|
|
// child process
|
|
|
|
if (pid == 0) {
|
|
|
|
printf("\n Child Process: \n");
|
|
|
|
for (i = 0; i < 5; i++) {
|
|
|
|
for (j = 0; j < 5 - i - 1; j++) {
|
|
|
|
if (strcmp(strings[j], strings[j + 1]) > 0){
|
|
|
|
strcpy(temp, strings[j]);
|
|
|
|
strcpy(strings[j], strings[j+1]);
|
|
|
|
strcpy(strings[j+1], temp);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
for (i = 0; i < 5; i++) {
|
|
|
|
printf("\n Child: %s \n", strings[i]);
|
|
|
|
}
|
|
|
|
|
|
|
|
printf("\n");
|
|
|
|
exit (00);
|
|
|
|
|
|
|
|
// parent process
|
|
|
|
} else if (pid > 0) {
|
|
|
|
wait(&status);
|
|
|
|
printf("\n Parent Process: \n");
|
|
|
|
for (i = 0; i < 5; i++) {
|
|
|
|
printf("\n Parent: %s \n", string_cpy[i]);
|
|
|
|
printf("%d",WEXITSTATUS(status));
|
|
|
|
}
|
|
|
|
|
|
|
|
// exception handling (catchall statement)
|
|
|
|
} else {
|
|
|
|
printf("THE SYSTEM ENCOUNTERED AN ERROR. Please try again later or debug the code. \n");
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|