標準/拡張機能 | C/C++ | 依存項目 |
---|---|---|
POSIX.1 |
両方 |
#define _POSIX_SOURCE
#include <unistd.h>
int dup(int fildes);
使用できる最も小さい番号の記述子である 新規ファイル記述子を戻します。新規ファイル記述子は、fildes と同じ オープン・ファイルを参照して、fildes と関連して いる可能性のある任意のロックを共用します。
fd = dup(fildes);
fd = fcntl(fildes,F_DUPFD,0);
詳しくは、fcntl() - オープン・ファイル記述子の制御を参照してください。正常に実行された場合、dup() は、新規ファイル記述子を戻します。
⁄* CELEBD05
This example duplicates an open file descriptor, using dup().
*⁄
#define _POSIX_SOURCE
#include <errno.h>
#include <sys⁄stat.h>
#include <sys⁄types.h>
#include <unistd.h>
#undef _POSIX_SOURCE
#include <stdio.h>
void print_inode(int fd) {
struct stat info;
if (fstat(fd, &info) != 0)
fprintf(stderr,"fstat() error for fd %d: %s¥n",fd,strerror(errno));
else
printf("The inode of fd %d is %d¥n", fd, (int) info.st_ino);
}
main() {
int fd;
if ((fd = dup(0)) < 0)
perror("&dupf error");
else {
print_inode(0);
print_inode(fd);
puts("The file descriptors are different but");
puts("they point to the same file.");
close(fd);
}
}
The inode of fd 0 is 30
The inode of fd 3 is 30
The file descriptors are different but
they point to the same file.