Reputation: 353
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);
}
Upvotes: 0
Views: 196
Reputation: 3162
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
.
Upvotes: 0
Reputation: 45654
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.
Upvotes: 3