问题
I'm trying to create a multi-level pipe, where the input is Linux commands (e.g. ls | sort) and the output is just the regular output when typed into a Linux console (essentially just use execlp to execute the commands).
I've attempted to create a program that works for 1 and 2 levels, but I can't seem to get the 2 level one to work, specifically with the command "ls | sort". The program just freezes. I also don't know how to continue beyond that and add more levels (required to support 16 total).
// the function has to return unless the command is "exit"
void process_cmd(char *cmdline) {
// exit program
if (strcmp(cmdline, "exit") == 0) {
printf("The shell program (pid=%d) terminates\n", getpid());
exit(0);
}
// separate the user input into the different commands using another
// defined function
char* strings[MAX_PIPE_SEGMENTS];
int x = 0;
int* numTokens = &x;
tokenize(strings, cmdline, numTokens, "|");
// 1 command
if (*numTokens == 1) {
pid_t pid = fork();
if (pid == 0) {
execlp(strings[0], strings[0], NULL);
} else {
wait(0);
return;
}
}
// 2 commands, this is the problem
int ps[*numTokens];
pipe(ps);
pid_t pid = fork();
if (pid == 0) {
pid_t pid2 = fork();
if (pid2 == 0) {
close(1);
dup2(ps[1], 1);
close(ps[0]);
execlp(strings[0], strings[0], NULL);
} else {
close(0);
dup2(ps[0], 0);
close(ps[1]);
wait(0);
execlp(strings[1], strings[1], NULL);
}
} else {
wait(0);
return;
}
}
来源:https://stackoverflow.com/questions/58374595/creating-a-multi-level-pipe-for-linux-commands