c - 为 Linux 命令创建多级管道
问题描述
我正在尝试创建一个多级管道,其中输入是 Linux 命令(例如 ls | sort),输出只是输入到 Linux 控制台时的常规输出(基本上只是使用 execlp 来执行命令)。
我试图创建一个适用于 1 级和 2 级的程序,但我似乎无法让 2 级工作,特别是使用命令“ls | sort”。该程序只是冻结。我也不知道如何继续并添加更多级别(总共需要支持 16 个级别)。
// 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;
}
}
解决方案
推荐阅读
- reactjs - 使用数据返回未定义更新状态
- javascript - 在 JavaScript 中同步加载和评估动态生成的脚本
- admob - 为什么我什至没有尝试使用与 AdMob 远程链接的任何东西时,AdMob 会搞砸我的基本音乐播放/暂停应用
- typescript - , IntelliJ 如何支持一些 TypeScript 编译器不支持的特性?
- string - 对字符串数组进行排序,以便稍后出现任何其他字符串的子字符串
- r - R使用循环将多个图表绘制为单个pdf
- python - 如何计算字符串中所有值的频率/出现次数
- typescript - 如何在声明文件的命名空间中键入循环引用?
- excel - 通过 vba 导入 csv 时将数字类型更改为文本类型
- mysql - MySQL 数据库中 SHOW TABLE STATUS 的 `engine` 列中的 NULL 是什么意思?