c - 如何在 C 中的 io 重定向后返回标准输入/输出
问题描述
我正在用 C 创建一个简单的 shell,其中一个功能是 IO 重定向。然而; 在完成重定向命令的执行后,我很难弄清楚如何返回标准输入/标准输出。
我尝试复制标准输入/输出,然后在主函数中再次使用它,如代码所示,但这不起作用。
void execute(char **args, bool flag)
{
pid_t pid;
int status;
int exc;
if ((pid = fork()) < 0) {
printf("forking child process failed\n");
}
else if (pid == 0) { /* for the child process: */
if(in_flag){
file_desc_in = open(sub2, O_RDONLY | O_CREAT);
chmod(sub2 , S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);
stdinCopy = dup(STDIN_FILENO);
dup2(file_desc_in, 0);
close(file_desc_in);
in = true;
}
else if(out_flag){
file_desc_out = open(sub2,O_WRONLY |O_APPEND | O_CREAT);
chmod(sub2 , S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH);
stdoutCopy = dup(STDOUT_FILENO);
dup2(file_desc_out, STDOUT_FILENO);
close(file_desc_out);
out = true;
}
exc = execvp(args[0], args); /* execute the command */
printf("exec failed!\n")
exit(EXIT_FAILURE)
}
if(flag){
pid_t childpid = wait(&status);
}
}
这部分在 main()
if(out){
dup2(stdoutCopy,STDOUT_FILENO);
close(stdoutCopy);
out = false;
}
else if(in){
dup2(stdinCopy,STDIN_FILENO);
close(stdinCopy);
in = false;
}
例如,当我将 ls 命令的输出重定向到某个文件 output.txt 时,重定向会起作用并且输出会显示在文件中,但是对于所有新输入的命令,所有输出都会转到同一个文件,而不是显示在终端上。
我该如何解决这个问题?
解决方案
推荐阅读
- sql - 查找按其他两列分组的列的前 n 个总和
- html - 我无法在我的父类中选择我的第二段
- excel - 从下拉列表中选择值时从另一张表中获取记录
- javascript - 如何在ckeditor5中添加音频(自定义)标签
- javascript - 如何从 safeHtml 获取 div 的 id?
- html - 如何删除或编辑周围的空白?
- javascript - 如何使用 PHP 发布以前的 Jquery ajax 搜索复选框?
- angular - 为什么在 Chrome 开发工具中看到 webpack 5 有重复的源映射?
- windows - 错误运行机器:作业:sample-google:错误运行 ping :套接字:权限被拒绝
- angular - 更新到 Angular 12 和 Jest 27.2.4 时的问题测试