我如何确保我正在开始的程序将其stdout写入我打开的FD?

问题描述 投票:1回答:1

我正在尝试为我的shell实现><重定向,但在我的情况下,假设我做ls > output.txt,它创建一个新文件但不会将其写入文件中。这是我的代码的预览:

    pid = fork();
    if (pid == 0){
        int i = 0;
        for (i=0; args[i]!='\0'; i++){
            int fd;
            if (strcmp(args[i], ">")==0){

                fd = open(args[i+1], O_CREAT|O_TRUNC | O_WRONLY, 0600);
                dup2(fd,  STDOUT_FILENO);
                close(fd);

            }
            if(strcmp(args[i], "<")==0){

                fd = open(args[i+1],O_RDONLY);
                dup2(fd,  STDOUT_FILENO);
                close(fd);
            }
c io-redirection
1个回答
0
投票

试试这个>>而不是>

'>>'追加到文件末尾

© www.soinside.com 2019 - 2024. All rights reserved.