Linux的dup与dup2函数

dup函数

函数原型:

int dup(int oldfd);

作用:
复制oldfd,返回新的文件描述符,这两个文件描述符执行相同的系统资源,而且新的文件描述符是操作系统给进程分配没有用到的数字最小的那个。

注意:这个复制操作,不会复制有关的文件描述符标志,比如说CLOSE_ONEXEC等。

代码实例:

#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

void print_inode(int fd) {
  struct stat info;
  if (fstat(fd, &info) != 0) {
    //fprintf(stderr, "fstat() error for fd %d: %s", fd, strerror(errno));
    perror("fstat() error\n");
  } else {
    printf("The inode of fd %d is %d\n", fd, (int)info.st_ino);
  }
}

int main() {
  int fd;
  if ((fd = dup(0)) < 0) {
    perror("dup() error\n");
  } else {
    print_inode(0);
    print_inode(fd);
    close(fd);
  }
  return 0;
}
/*
The inode of fd 0 is 3
The inode of fd 3 is 3
*/

dup2函数

函数原型

int dup2(int oldfd, int newfd);

作用同上,不过是把复制后的fd赋值给newfd,也不能复制文件描述的标记。

两者失败都会返回-1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值