c - 如何将输入/输出重定向放在新创建的 c shell 中?

标签 c linux shell io io-redirection

我想知道是否有人可以指出正确的方向,告诉我如何做到这一点?例如,如果我写“ls > contents.txt”,我希望将 ls 的输出写入 content.txt。

这就是我目前所拥有的。

 #include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <ctype.h>

void  parse(char *line, char **argv)
{
     while (*line != '\0') { 
          while (*line == ' ' || *line == '\t' || *line == '\n')
               *line++ = '\0';     
          *argv++ = line;          
          while (*line != '\0' && *line != ' ' && 
                 *line != '\t' && *line != '\n') 
               line++;            
     }
     *argv = '\0';               
}

void  execute(char **argv)
{
     pid_t  pid;
     int    status;

     if ((pid = fork()) < 0) {     
          printf("*** ERROR: forking child process failed\n");
          exit(1);
     }
     else if (pid == 0) {          
          if (execvp(*argv, argv) < 0) {     
               printf("*** ERROR: exec failed\n");
               exit(1);
          }

     }
     else {                                 
          while (wait(&status) != pid)      
               ;
     }
}
void main(char *envp[])
{
    char line[1024];
    char *argv[64];
    while (1){
      printf("shell>>");
      gets(line);
      printf("\n");
      parse(line, argv);
      if (strcmp(argv[0], "exit")==0)
    exit(0);
      execute(argv);
    }
}

最佳答案

在测试 pid==0 和运行 execvp() 之前,您需要这样的代码:

int fd=open(outputfile,O_WRONLY|O_CREAT); 
dup2(fd,1);

这实际上会将 execvp() 运行的程序的标准输出设置为这个新文件。您将必须修改解析代码以查找“>”并将其后的内容解析为文件名并存储在输出文件中。 您还想做一些额外的检查以确保新文件打开正常等。

关于c - 如何将输入/输出重定向放在新创建的 c shell 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28331981/

相关文章:

c - libtomcrypt 的 RSA 签名验证失败

linux - 无法使用 input.h Linux 生成写入设备内核的击键

c - 以破折号为前缀的命令行参数有什么特别之处吗?

将 gets() 更改为 txt 文件输入

c - 我的第二个 scanf 不起作用 - 我该怎么办?

php - 是否可以在现有的Alpine 3.12 Docker镜像上安装PHP7.4?

python - 如何在 Tkinter 中创建一个类似 IDLE 的小型 Python Shell?

您可以使用 Windows 操作系统和 Dev-C++ IDE 为 Linux 编写 shell 吗? shell 在两种操作系统上的工作方式是否相同?

C 函数实现 - 带指针与不带指针

linux - ls: 未找到命令 BASH