c - 当我不想覆盖时我的 shell 实现

标签 c linux shell stdout

我目前有一个用 C 编写的 Bash 的基本实现。但是,当我尝试两次重定向标准输出时遇到问题。相关代码如下:

读入每个命令:

for ( ; ; ) {
        printf ("(%d)$ ", nCmd);                // Prompt for command
        fflush (stdout);
        if ((line = getLine (stdin)) == NULL)   // Read line
            break;                              //   Break on end of file

        list = lex (line);
        free (line);
        if (list == NULL) {
            continue;
        } else if (getenv ("DUMP_LIST")) {      // Dump token list only if
            dumpList (list);                    //   environment variable set
            printf ("\n");
        }

        cmd = parse (list);                     // Parsed command?
        freeList (list);
        if (cmd == NULL) {
            continue;
        } else if (getenv ("DUMP_TREE")) {      // Dump command tree only if
            dumpTree (cmd, 0);                  //   environment variable set
            printf ("\n");
        }

        process (cmd);                          // Execute command
        freeCMD (cmd);                          // Free associated storage
        nCmd++;                                 // Adjust prompt
    }

我们是我的代码的 shell 部分搞砸了:

if (cmdList->type==SIMPLE)
    {
        pid_t fork_result;
            fork_result = fork();
            if (fork_result < 0) {
                fprintf(stderr, "Fork failure");
                exit(EXIT_FAILURE);
            }
            if (fork_result == 0) {
                if (cmdList->fromType==RED_IN)
                {
                    int fe = open(cmdList->fromFile, O_RDONLY, 0);
                    dup2(fe, 0);
                    close(fe);
                }
                if ((cmdList->toType==RED_OUT) || (cmdList->fromType==RED_APP))
                {
                    int fd = open(cmdList->toFile, O_CREAT | O_WRONLY, 0666);
                    dup2(fd, 1);
                    close(fd);
                }
                execvp(cmdList->argv[0],cmdList->argv);
                exit(EXIT_FAILURE);
            }
            else {
                int status;
                wait(&status);
            }

    }

当我阅读一个简单的命令时,最后一段代码完全符合我的预期。但是,当我使用 for 循环尝试两次重定向 stout 时,问题就出现了。例如,我尝试运行:

cat Tests/star.wars > +Bash.tmp
cat +Bash.tmp

cat Tests/stk.txt   > +Bash.tmp
cat +Bash.tmp

第一个命令将“ABC”写入 Bash.tmp。但是,当我运行第二个命令时,我希望它返回“DE”。但是,我得到“DEC”作为输出。怎么了?

最佳答案

O_WRONLY 是“只写”权限。 O_TRUNC 是在打开时截断文件的内容。 – 伊坦·赖斯纳

关于c - 当我不想覆盖时我的 shell 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27518938/

相关文章:

linux - 用top判断Linux进程内存

linux - 将文本文件合并为一个文本文件

用于在压缩的 .gz 文件中搜索的 Unix 脚本

linux - 删除名称为 mongoID 且早于特定时间戳的文件

c++ - C hack 用于存储占用 1 位空间的位?

c - 在c中解析char数组

c - 如何使用 SIMD 加速 XOR 两 block 内存?

c++ - C 套接字发送/接收缓冲区类型

linux - 如何使 xterm 命令行像 vim 一样工作

c# - C++ Client 和 C# Server 通过 Network Stream 通信