#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_COMMAND_LEN 256
#define MAX_ARGS 10
int main() {
int pipefd[2];
pid_t pid;
char *args[MAX_ARGS];
char command[MAX_COMMAND_LEN];
int status;
int i, j;
// 创建一个匿名管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建并运行子进程
for (i = 0; i < 5; i++) {
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
// 子进程通过管道读取数据
close(pipefd[1]); // 关闭写端
while (fgets(command, MAX_COMMAND_LEN, stdin) != NULL) {
if (command[strlen(command) - 1] == '\n') {
command[strlen(command) - 1] = 0;
}
if (strcmp(command, "exit") == 0) {
close(pipefd[0]);
exit(EXIT_SUCCESS);
}
// 解析命令行参数
j = 0;
args[j++] = "echo_wrapper";
char *token = strtok(command, " ");
while (token != NULL && j < MAX_ARGS - 1) {
args[j++] = token;
token = strtok(NULL, " ");
}
args[j] = NULL;
// 通过管道将命令发送给父进程
if (write(pipefd[1], args, sizeof(args)) == -1) {
perror("write");
close(pipefd[0]);
exit(EXIT_FAILURE);
}
}
close(pipefd[0]);
close(pipefd[1]);
exit(EXIT_SUCCESS);
}
}
// 父进程
close(pipefd[0]); // 关闭读端
while (fgets(command, MAX_COMMAND_LEN, stdin) != NULL) {
if (command[strlen(command) - 1] == '\n') {
command[strlen(command) - 1] = 0;
}
if (strcmp(command, "exit") == 0) {
close(pipefd[1]);
break;
}
// 解析命令行参数
j = 0;
args[j++] = "echo_wrapper";
char *token = strtok(command, " ");
while (token != NULL && j < MAX_ARGS - 1) {
args[j++] = token;
token = strtok(NULL, " ");
}
args[j] = NULL;
// 通过管道将命令发送给子进程
if (write(pipefd[1],
评论已关闭