Question

Can someone please tell me why this basic implementation of dup2 is not working. When i run it the output is not redirected but is simply printed on the standard output.

   #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);

     }
Was it helpful?

Solution

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

Please mind operator precedence (< trumps =), use parentheses. You are setting fd to 0 (stdin) on success.

write(STDOUT_FILENO,buf,nread);

This line fails because stdin is not open for writing.

OTHER TIPS

This is because fd is set after relational operation so use parenthesis to avoid it as,

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

since you dint use these parenthesis to assign the value for fd first then perform the comparison, fd was getting set to 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top