#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#define MAX_LINE 80
int main(int argc, char *argv[]) {
int fd[2];
pid_t pid1, pid2, pid3;
// Create a pipe
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
// Create the first child process
pid1 = fork();
if (pid1 < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid1 == 0) {
// Child process 1: display command line arguments
printf("Child process 1 (pid: %d):\n", getpid());
for (int i = 0; i < argc; i++) {
printf("argv[%d]: %s\n", i, argv[i]);
}
} else {
// Parent process
wait(NULL);
// Create the second child process
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid2 == 0) {
// Child process 2: communicate with parent via pipe
close(fd[0]); // Close reading end of pipe
char msg[] = "Hello from child process 2";
write(fd[1], msg, strlen(msg) + 1);
close(fd[1]);
} else {
// Parent process
wait(NULL);
close(fd[1]); // Close writing end of pipe
char msg[MAX_LINE];
read(fd[0], msg, MAX_LINE);
printf("Parent process received: %s\n", msg);
close(fd[0]);
// Create the third child process
pid3 = fork();
if (pid3 < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid3 == 0) {
// Child process 3: execute another C program
execlp("./hello", "hello", NULL);
} else {
// Parent process
wait(NULL);
}
}
}
return 0;
}
0 Comments