将标准输出重定向到文件 [英] Redirect stdout to a file

查看:515
本文介绍了将标准输出重定向到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在C语言中执行bash命令ls>foo.txt的等效操作.

I am trying to do the equivalent of the bash command ls>foo.txt in C.

下面的代码将输出重定向到变量.

The code bellow redirects the output to a variable.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>

int main(){
  int pfds[2];
  char buf[30];

  pipe(pfds);

  if (!fork()) {
    close(pfds[0]);
     //close(1);//Close stdout
    //dup(pfds[1]);
    //execlp("ls", "ls", NULL);
    write(pfds[1], "test", 5); //Writing in the pipe
    exit(0);
  } else {
    close(pfds[1]);  
    read(pfds[0], buf, 5); //Read from pipe
    wait(NULL);
  }
  return 0;
}

注释行指的是重定向所必需的那些操作. 我应该怎么做才能将ls的输出重定向到foo.txt?

The comments lines refer to those operations that I believe that are required for the redirection. What should I change to redirect the output of ls to foo.txt?

推荐答案

您的代码本质上的作用是打开一个管道,然后派生该进程,并在子进程中(在注释的代码中)关闭stdout,将管道复制到stdout并执行和ls命令,然后(在非注释代码中)将4个字节写入管道.在父进程中,您将从管道中读取数据,并等待子进程完成.

What your code essentially does is that you open a pipe, then fork the process and in the child process (in commented code) close stdout, duplicate the pipe to stdout and execute and ls command, and then (in non-commented code) write 4 bytes to the pipe. In the parent process, you read data from the pipe and wait for the completion of the child process.

现在,您要将标准输出重定向到文件.您可以通过使用open()系统调用打开文件,然后将该文件描述符复制到stdout来实现.像这样的东西(我还没有测试过,所以要提防代码中的错误):

Now you want to redirect stdout to a file. You can do that by opening a file using the open() system call and then duplicating that file descriptor to stdout. Something like (I haven't tested this so beware of bugs in the code):

int filefd = open("foo.txt", O_WRONLY|O_CREAT, 0666);
if (!fork()) {
  close(1);//Close stdout
  dup(filefd);
  execlp("ls", "ls", NULL);
} else {
  close(filefd);
  wait(NULL);
}
return 0;

但是,您也可以按照其他答案的建议使用freopen.

However, you can also use the freopen as suggested by the other answer.

但是,我对您的代码和修改后的代码有一些担忧:

However, I have several concerns of your code and of my modified code:

  • pipe()和open()系统调用可能会失败.您应该始终检查系统调用失败.

  • The pipe() and open() system calls can fail. You should always check for system call failure.

fork()系统调用可能失败.同上.

The fork() system call can fail. Ditto.

dup2()代替dup();否则,如果stdin没有打开,则代码将失败,因为它会复制到第一个可用的文件描述符.

dup2() can be used instead of dup(); otherwise the code will fail if stdin is not open as it duplicates to the first available file descriptor.

execlp()系统调用可能失败.同上.

The execlp() system call can fail. Ditto.

我认为wait()可以被信号(EINTR)中断.建议将其包装在一个包装器中,该包装器如果被信号中止(errno == EINTR)重试系统调用.

I think wait() can be interrupted by a signal (EINTR). It's recommended to wrap it around a wrapper that retries the system call if it's aborted by a signal (errno == EINTR).

这篇关于将标准输出重定向到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆