1

我在 c 中实现了一个 shell,并且很难将命令的输出重定向到文件。当我将输出发送到文件时,它似乎可以工作,但文件没有打开,当我运行 ls -l 时,它显示以下内容:

---------x   1 warp  staff   441 Nov  4 20:15 output.txt

这是我的代码的一部分

pid = fork();
if(pid == 0) 
{ /* child process */

    if(redirFlag)
    {
        int fdRedir = open(redirectName, O_WRONLY | O_CREAT );
        if( fdRedir < 0){
            perror("Can't Open");
            exit(1);
        }

        if(dup2(fdRedir, STDOUT_FILENO) == -1){
            perror("dup2 failed");
            exit(1);
        }


    } 
    execvp(supplement[0], supplement);
    /* return only when exec fails */
    perror("exec failed");
    exit(-1);
4

1 回答 1

2

的原型open是:

#include <fcntl.h>  
int open(const char *path, int oflag, ...);

创建文件时,您应该给出文件模式。

int open(const char *path, int oflags, mode_t mode);

在您的代码中,文件是用标志打开的,O_CREAT但没有给出文件模式。所以你没有权限对其进行操作。创建新文件时尝试指明文件权限:

int fdRedir = open(redirectName, O_WRONLY | O_CREAT, 0644);
于 2013-11-05T01:35:03.080 回答