简体   繁体   English

dup返回值始终为零

[英]dup return value is always zero

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) : 我想知道为什么dup在以下代码中总是返回零(在打开文件的情况下,连续执行10 dup即可):

#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: 当我运行程序(在Linux 2.6.32-279.19.1.el6.i686,Netbsd或Solaris 5.9上)时,我得到以下结果:

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"?! dup的返回值始终为“ 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. 如果出错,则返回-1,并正确设置errno。

I don't understand why i get always "0", knowing that i didn't use the close operation. 我不知道为什么我总是使用“ 0”,因为我没有使用关闭操作。

Please, help. 请帮忙。

The error is in your condition: 错误是在您的情况下:

(fdd = dup(fdo) < 0)

The variable fdd becomes the result of dup(fdo) < 0 . 变量fdd成为dup(fdo) < 0 You need to check your parentheses: 您需要检查括号:

(fdd = dup(fdo)) < 0 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM