c - 简单的 dup2 功能不适用于 ubuntu

标签 c unix dup2

谁能告诉我为什么 dup2 的这个基本实现不起作用。 当我运行它时,输出不会被重定向,而只是打印在标准输出上。

   #include<unistd.h>
   #include<stdio.h>
   #include<sys/types.h>
   #include<fcntl.h>

   void main(int argc,char *argv[] )
   {
      int fd,nread;
      char buf[4096];
      if(fd=open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IROTH|S_IRGRP)<0)
          printf("error opening");

      printf("fd=%d",fd);
      if(dup2(fd,STDOUT_FILENO)==-1)
            printf("error in duplicating");

       while(nread=read(STDIN_FILENO,buf,4096))
           write(STDOUT_FILENO,buf,nread);

     }

最佳答案

if(fd=open(argv[1],O_WRONLY|O_CREAT|O_TRUNC,S_IRUSR|S_IWUSR|S_IROTH|S_IRGRP)<0)

请注意运算符优先级( < 胜过 = ),使用括号。您正在设置 fd成功时为 0(标准输入)。

write(STDOUT_FILENO,buf,nread);

此行失败,因为标准输入未打开以供写入。

关于c - 简单的 dup2 功能不适用于 ubuntu,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23249044/

相关文章:

c - 与dup2(),exec()和管道混淆

c - 了解并尝试使用 Valgrind 进行 C 编程。

c - 为什么在 C 中转换后 int 的值会发生变化

shell - SSH : Remotely run a script and stay there

vb.net - 将unix时间转换为DateTime

c++ - 将 FROM stderr 重定向到另一个文件描述符

c - 为数组中的每个元素添加值?

c - 利用 C 中的 system() 调用

database - Linux 中的 TNS 条目

vfork后可以调用dup2吗?