2011-04-01 84 views
3

我正在一个简单的shell,但现在我只是想了解重定向。我只是硬编码一个LS命令,并试图将它写入文件。目前,ls运行,并且输出文件被创建,但输出仍然到stdout并且文件是空白的。我很困惑,为什么。提前致谢。将fork重定向到文件后叉()

这里是我的代码:

int main() 
{ 
    int ls_pid; /* The new process id for ls*/ 
    char *const ls_params[] = {"/bin/ls", NULL}; /* for ls */ 
    int file; /* file for writing */ 

    /* Open file check user permissions */ 
    if (file = open("outfile", O_WRONLY|O_CREAT) == -1) /* , S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP */ 
    { 
     perror("Failed to open file"); 
     _exit(EXIT_FAILURE); 
    } 

    ls_pid = fork(); /* Create new process for ls */ 

    if (ls_pid == -1) /* error check */ 
    { 
     perror("Error forking ls (pid == -1)"); 
     _exit(EXIT_FAILURE); 
    } 
    else if (ls_pid == 0) /* Child of ls */ 
    { 
     /* Redirect output to file */ 
     if (dup2(file, STDOUT_FILENO) == -1) /* STDOUT_FILENO = 1 */ 
     { 
      perror("Error duping to file"); 
      _exit(EXIT_FAILURE); 
     } 
     close(file); 

     execvp("ls", ls_params); /* create the sort process */ 
     /* execlp("ls", "ls", NULL); */ 

     /* if this does not end the program, something is wrong */ 
     perror("Exec failed at sort"); 
     _exit(EXIT_FAILURE); 
    } 
    else /* ls parent (1) */ 
    { 
     /* wait for child */ 
     if (wait(NULL) == -1) 
     { 
      perror("fork failed on parent"); 
      _exit(EXIT_FAILURE); 
     } 
    } 

} 
+0

固定。它是我的公开命令周围的一部分。 – 2011-04-01 19:46:25

回答

0

我看不出有什么问题。我自己尝试了你的代码。它的工作原理!我的简化代码如下所示:

int main(void) { 
    int fd; 

    char* const param[] = {"/bin/ls", NULL}; 

    fd = open("outfile", O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); 

    if (fd < 0) { 
     perror("open failed\n"); 
     exit(0); 
    } 

    pid_t pid = fork(); 

    if (pid < 0) { 
     perror("fork failed\n"); 
     exit(0); 
    } 
    else if (pid == 0) { 
     dup2(fd, STDOUT_FILENO); 

     close(fd); 

     execvp("ls", param); 
    } 
    else { 
     wait(NULL); 
    } 
} 

我编译一个执行它,并在outfile中找到预期的结果。

唯一的区别是我用S_IRUSER | S_IWUSER权限选项,否则打开失败。我在你的代码中看到类似的东西,但不知何故,你评论他们...