Question

I would to know why does dup always return zeroes in the following code (in which a file is opened, than 10 dup are done successively) :

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

void main()
{
        int i,fdo,fdd;

        if((fdo = open("test", O_RDWR | O_CREAT, 0666)) < 0)
        {
                        perror("main open");
                        return;
        }

        printf("main open: %d\n",fdo);


        for(i=0; i< 10;i++)
        {
                if((fdd = dup(fdo) < 0 )) {
                        perror("dup");
                        return ;
                }
                printf("opened %d, duped: %d \n", fdo,fdd);

        }

}

When i run the program (on linux 2.6.32-279.19.1.el6.i686, Netbsd or Solaris 5.9) , i get the following results:

main open: 3
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 
opened 3, duped: 0 

The return value of dup is always "0"?!

Althought the man page state that the return value should be the file descriptor:

RETURN VALUE On success, these system calls return the new descriptor. On error, -1 is returned, and errno is set appropriately.

I don't understand why i get always "0", knowing that i didn't use the close operation.

Please, help.

Was it helpful?

Solution

The error is in your condition:

(fdd = dup(fdo) < 0)

The variable fdd becomes the result of dup(fdo) < 0. You need to check your parentheses:

(fdd = dup(fdo)) < 0 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top