core: add all the required files
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
/* Experiment 01 — file descriptors are small integers, and they get reused.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 01_fds.c -o 01_fds
|
||||
* Run: ./01_fds
|
||||
*
|
||||
* Observe: stdin/stdout/stderr are 0/1/2 (they exist before your program runs).
|
||||
* A file and a socket both get the next free numbers — 3, 4 — because the
|
||||
* kernel reuses the smallest free slot. Close them and open again: the numbers
|
||||
* come back. That's the whole "fd" concept.
|
||||
*/
|
||||
#include <fcntl.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/socket.h>
|
||||
#include <unistd.h>
|
||||
#include <netinet/in.h>
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int file_fd; // normal file
|
||||
int sock_fd; // network file
|
||||
|
||||
printf("always there: stdin=%d stdout=%d stderr=%d\n", 0, 1, 2);
|
||||
|
||||
file_fd = open("/etc/hostname", O_RDONLY); // open the hostname file
|
||||
sock_fd = socket(AF_INET, SOCK_STREAM, 0);// creat ea socket on the internet
|
||||
printf("first round: file=%d socket=%d\n", file_fd, sock_fd);
|
||||
close(file_fd);
|
||||
close(sock_fd);
|
||||
|
||||
file_fd = open("/etc/hostname", O_RDONLY);
|
||||
sock_fd = socket(AF_INET, SOCK_STREAM, 0);// socket(ipv4, tcp connection, 0)
|
||||
printf("after close: file=%d socket=%d <- reused the smallest free slots\n",
|
||||
file_fd, sock_fd);
|
||||
close(file_fd);
|
||||
close(sock_fd);
|
||||
return (0);
|
||||
}
|
||||
Reference in New Issue
Block a user