例子
dup的使用,主要是保存的作用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread>
int main(int argc, cha *agrv[])
{
int fd = open(argv[1], O_RDONLY);
int newfd = dup(fd);
printf("newfd = %d\n", newfd);
return 0;
}
dup2的使用,可以打开进行的fd
// 可以创建新的文件描述符指向之前的文件内存
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread>
int main(int argc, cha *agrv[])
{
int fd1 = open(argv[1], O_RDWR);
int fd2 = open(argv[2], O_RDWR);
int fdret = dup2(fd1, fd2);
printf("fdret = %d\n", fdret);
int ret=write(fd2, "1234567", 7);
printf("ret=%d\n", ret);
dup2(fd1, STDOUT_FILENO);
printf("---------------123\n");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <pthread>
int main(int argc, cha *agrv[])
{
int fd1 = open(argv[1], O_RDWR);
printf("fd1=%d\n", fd1);
int newfd = fcntl(fd1, F_DUPFD, 0);
// 0被占用,fcntl使用文件描述符表中可用的最小描述符进行返回
printf("newfd=%d\n", newfd);
int newfd = fcntl(fd1, F_DUPFD, 7);
// 7被占用,fcntl会返回一个大于7的文件描述符
return 0;
}
PCB进程控制模块
成员:文件描述符。
文件描述符:0,1,2,3,4,...... 1023
0 - STDIN_FILENO 输入
1 - STDOUT_FILEINO 输出
2 - STDERR_FILENO
产生堵塞的场景。读设备文件,读取网络文件(读常规文件无堵塞概念)
/dev/tty -- 终端文件。
open("/dev/tty", O_RDWR|O_NONBLOCK) ---- 设置 /dev/tty 为非堵塞状态,默认为堵塞状态
dup和dup2的区别和具体使用方法_文件描述符和堵塞非堵塞
原文:https://www.cnblogs.com/fandx/p/12518323.html