【问题标题】:how to redirect output from cd in a shell written in C如何在用 C 编写的 shell 中重定向 cd 的输出
【发布时间】:2013-03-27 19:22:26
【问题描述】:

我正在用 C 编写一个基本的 shell,我已经实现了所有重定向运算符,但是,当我尝试重定向“cd”时,我遇到了这个问题:

cd 在没有任何输出重定向的情况下完美运行,但是

当我尝试做这样的事情时:

cd inexistant_directory > output_file

没有创建输出文件,在 bash 中,运行该命令会重定向标准输出,正如我之前所说的,使用外部命令的重定向运算符效果很好

当我遇到 cd 命令时,我调用了

char*path = get_path(parameters);  //implemented by me, works on rest of the cases
int  ret =chdir(path);

我不在子进程中调用它,而是在父进程(shell进程本身)中调用它

我做错了什么?

谢谢,

PS:我运行它的操作系统是 Ubuntu 12.10,但是代码是 POSIX 兼容的

LE:我无法发布整个代码,因为它大约有 600 行,

这是我的逻辑

if(internal_command) {
     //do quit, exit or cd
} else if (variable_assignemt){
     //do stuff
} else {
    // external command
    pid = fork();
    if(pid == -1) {
        //crash
    } else if (pid == 0) {
        do_redirects()
        call_external_cmd
     }
    default : 
        wait(pid, &status);

所以,我认为要解决这个问题,我需要在 parrent(shell 进程)中重定向标准输出 并在命令执行后恢复

【问题讨论】:

  • 你得到的输出是什么?
  • 显示更多你的shell代码。它可能有错误。
  • shell 中的重定向执行dup2 或dup 系统调用,通常将STDOUT 重定向到另一个文件描述符,在这种情况下将是输出文件。
  • 嗯...如果你没有在你的shell中实现这个功能,你为什么期望它能够工作?
  • 如果 get_path 不知道如何进行输出重定向,我不希望有一个。

标签: c linux shell


【解决方案1】:

在父进程(shell)中不重定向标准输出确实是导致 cd 的不良行为,我的解决方案如下:

   if(we_have_out_redirection == 1) {
       if(out != NULL) {

       char *outParrent = out;

           fflush(stdout);

       outBackup = dup(STDOUT_FILENO); //I save stdout for future restoration
       int fd = open(outParrent, O_WRONLY | O_CREAT | O_TRUNC, 0644); //open output file
       int rc;
           rc = dup2(fd, STDOUT_FILENO); //redirect stdout

    retval = chdir(out); //execute cd command

        //restore stdout
    close(fd); 
    fflush(stdout);
    rc = dup2(outBackup, 1);
    close(outBackup);
   }
}

感谢 Jake223 指出我忘记在 parrent 中重定向!

【讨论】:

    猜你喜欢
    • 2011-04-26
    • 2016-03-10
    • 2014-06-03
    • 1970-01-01
    • 2012-02-23
    • 2015-04-04
    • 1970-01-01
    • 1970-01-01
    • 2010-09-11
    相关资源
    最近更新 更多