#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define BUFFER_SIZE 100
void childProcessOne(int argc, char *argv[]) {
printf("Child Process 1 (PID: %d):\n", getpid());
for (int i = 0; i < argc; i++) {
printf("Argument %d: %s\n", i, argv[i]);
}
}
void childProcessTwo(int fd[]) {
char msg[] = "Greetings from Child Process 2!";
close(fd[0]);
write(fd[1], msg, strlen(msg) + 1);
close(fd[1]);
}
void parentProcess(int fd[]) {
char buffer[BUFFER_SIZE];
close(fd[1]);
read(fd[0], buffer, BUFFER_SIZE);
printf("Parent Process Received: %s\n", buffer);
close(fd[0]);
}
void childProcessThree() {
printf("Child Process 3 Executing Another C Program...\n");
execlp("./other_program", "other_program", NULL);
}
int main(int argc, char *argv[]) {
int pipe_fd[2];
pid_t pid1, pid2, pid3;
if (pipe(pipe_fd) == -1) {
fprintf(stderr, "Pipe Creation Failed!\n");
return 1;
}
pid1 = fork();
if (pid1 < 0) {
fprintf(stderr, "Fork for Child Process 1 Failed!\n");
return 1;
} else if (pid1 == 0) {
childProcessOne(argc, argv);
} else {
wait(NULL);
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork for Child Process 2 Failed!\n");
return 1;
} else if (pid2 == 0) {
childProcessTwo(pipe_fd);
} else {
wait(NULL);
parentProcess(pipe_fd);
pid3 = fork();
if (pid3 < 0) {
fprintf(stderr, "Fork for Child Process 3 Failed!\n");
return 1;
} else if (pid3 == 0) {
childProcessThree();
} else {
wait(NULL);
}
}
}
return 0;
}
0 Comments