Function dup2(int oldfd, int newfd) fails in for() loop

173 views Asked by At

I tried this for fun to see if it works but eventually it does not.

    i = open("something", O_RDWR);
    for(i ; i<10 ; i++);
    {
            if(dup2(i, i+1 ) == -1 )
            {
                  printf("Dup failed\n");
                  exit(1);
            }

    }

I have straced the executable and the output is this:

open("something", O_RDWR)                   = 3
dup2(10, 11)                  = -1 EBADF (Bad file descriptor)

It seems as if only the last dup operation was executed!

The funny thing is that when I dup without a loop it works perfectly:

i = open("something", O_RDWR);
dup2(i,i+1);
i++;
dup2(i,i+1);
i++;
dup2(i,i+1);
i++;
dup2(i,i+1);
i++;
dup2(i,++i);

Output of strace:

open(".ping", O_RDWR)                   = 3
dup2(3, 4)                              = 4
dup2(4, 5)                              = 5
dup2(5, 6)                              = 6
dup2(6, 7)                              = 7
dup2(7, 8)                              = 8

What is the cause of dup failing in the for loop? Is there any error that I have missed?

2

There are 2 answers

1
AudioBubble On BEST ANSWER

It's the spurious terminating ; in line2 - remove it! Your loop will run until 10 while doing nothing (the final semicolon means an empty statement), and then the command in braces executed once.

0
user1794469 On

You have a typo in your for loop:

for(i ; i<10 ; i++);

should be

for(i ; i<10 ; i++)