Skip to content

Instantly share code, notes, and snippets.

@qqwqqw689
Last active March 17, 2024 15:31
Show Gist options
  • Save qqwqqw689/413767cbe2f5ff7e3b50a14855088383 to your computer and use it in GitHub Desktop.
Save qqwqqw689/413767cbe2f5ff7e3b50a14855088383 to your computer and use it in GitHub Desktop.
dup2
#define _POSIX_SOURCE
// If you define this macro, then the functionality from
// the POSIX.1 standard (IEEE Standard 1003.1) is available
#include <errno.h>
#include <fcntl.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;
// int fstat(int fd, struct stat *buf);
// Return information about a file.
// char *strerror(int errnum);
// The strerror() function returns a pointer to a string that
// describes the error code passed in the argument errnum.
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);
}
int main() {
int fd;
char fn[]="dup2.file";
// creat(path, mode) <==> open(path, O_WRONLY|O_CREAT|O_TRUNC, mode)
// O_WRONLY <==> write-only
// O_CREAT <==> If pathname does not exist, create it as a regular file.
// O_TRUNC <==> see doc
// mode applies only to future accesses of the newly created file
// S_IWUSR <==> 00200 user has write permission
if ((fd = creat(fn, S_IWUSR)) < 0)
perror("creat() error");
else {
print_inode(fd);
// int dup2(int oldfd, int newfd);
//
if ((fd = dup2(0, fd)) < 0)
perror("dup2() error");
else {
puts("After dup2()...");
print_inode(0);
print_inode(fd);
puts("The file descriptors are different but they");
puts("point to the same file which is different than");
puts("the file that the second fd originally pointed to.");
close(fd);
}
// int unlink(const char *pathname);
// unlink() deletes a name from the filesystem.
unlink(fn);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment