For some I/O, like terminal I/O, socket, mag tape,etc. We can not operate them with system calls like: read, write, lseek. We need to use ioctl to handle them.
Definition:
ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/bits/ioctls.h
/* Routing table calls. */
#define SIOCADDRT 0x890B /* add routing table entry */
#define SIOCDELRT 0x890C /* delete routing table entry */
#define SIOCRTMSG 0x890D /* call to routing system */
/* Socket configuration controls. */
#define SIOCGIFNAME 0x8910 /* get iface name */
#define SIOCSIFLINK 0x8911 /* set iface channel */
#define SIOCGIFCONF 0x8912 /* get iface list */
......
ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/ioctl.h
......
/* Perform the I/O control operation specified by REQUEST on FD.
One argument may follow; its presence and type depend on REQUEST.
Return value depends on REQUEST. Usually -1 indicates error. */
extern int ioctl (int __fd, unsigned long int __request, ...) __THROW;
......
2. /dev/fd/n
opening the /dev/fd/n is equivalent to duplicating file descriptor n, assuming n is already open.
fileio.c:
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
int main(int argc, char *argv[])
{
int fd;
char buff[] = "Hello world!";
// We are duplicating the file descriptor 0, after this call
// file descriptor 0 and new fd will point to the same file
// table entry
if((fd = open("/dev/fd/0", O_RDWR)) == -1) {
printf("open error!\n");
exit(1);
}
printf("fd: %d\n", fd);
// read from the standard input
if(read(fd, buff, 12) < 0) {
printf("read error!\n");
exit(2);
}
// Write information to standard output
if(write(STDOUT_FILENO, buff, 12) != 12) {
printf("write error!\n");
exit(2);
}
exit(0);
}
shell:
After runnign io.out, the program stops to let us input. We put in "Hello fire!", it then output the string to standard output.
ubuntu@ip-172-31-23-227:~$ ./io.out
fd: 3
Hello fire!
Hello fire!
Current implementation:
At the current system, we only have 3 file descriptors existing at /dev/fd.
ubuntu@ip-172-31-23-227:~$ sudo ls -lrt /dev/fd/*
ls: cannot access /dev/fd/255: No such file or directory
ls: cannot access /dev/fd/3: No such file or directory
lrwx------ 1 root root 64 Aug 19 00:51 /dev/fd/2 -> /dev/pts/0
lrwx------ 1 root root 64 Aug 19 00:51 /dev/fd/1 -> /dev/pts/0
lrwx------ 1 root root 64 Aug 19 00:51 /dev/fd/0 -> /dev/pts/0
Other usage:
1) "cat -" means outputting the content from standard input, but it is very ugly and confusing
2) "cat /dev/fd/0" means same thing, but this way is more straightforward. It specify that it will output the content from file descriptor 0, which is standard input.
ubuntu@ip-172-31-23-227:~$ cat -
Hello world!
Hello world!
^C
ubuntu@ip-172-31-23-227:~$ cat /dev/fd/0
Hello world!
Hello world!
^C
No comments:
Post a Comment