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);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/* Experiment 02 — bind + listen without accept: the kernel queues connections
|
||||
* for you. This shows what "backlog" and "someone connected" really mean.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 02_bind_listen.c -o 02_bind_listen
|
||||
* Run: ./02_bind_listen 8081 (Ctrl-C to stop)
|
||||
*
|
||||
* In other terminals:
|
||||
* ss -tlnp | grep 8081 -> your LISTEN socket, with backlog info
|
||||
* nc -v 127.0.0.1 8081 -> nc says "succeeded"! even though this
|
||||
* program never calls accept()
|
||||
* ss -tnp | grep 8081 -> the connection sits ESTABLISHED in the
|
||||
* accept queue, waiting for accept()
|
||||
*
|
||||
* Lesson: TCP handshakes are completed by the KERNEL. accept() only dequeues
|
||||
* an already-established connection. "nc connects" != "my code accepted it".
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct sockaddr_in addr; // socket information
|
||||
int sfd; // socket file discriptor
|
||||
|
||||
if (argc != 2) // check the arg cound
|
||||
{
|
||||
fprintf(stderr, "usage: %s PORT\n", argv[0]);
|
||||
return (1);
|
||||
}
|
||||
setvbuf(stdout, NULL, _IOLBF, 0); //empty the stdout buffer
|
||||
sfd = socket(AF_INET, SOCK_STREAM, 0); // create a socket
|
||||
if (sfd < 0)
|
||||
{
|
||||
perror("socket");
|
||||
return (1);
|
||||
}
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET;
|
||||
addr.sin_addr.s_addr = htonl(2130706433); /* 127.0.0.1 */
|
||||
addr.sin_port = htons(atoi(argv[1]));
|
||||
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
perror("bind");
|
||||
return (1);
|
||||
}
|
||||
if (listen(sfd, 10) < 0)
|
||||
{
|
||||
perror("listen");
|
||||
return (1);
|
||||
}
|
||||
printf("listening on 127.0.0.1:%s (fd %d) — and I will NEVER accept.\n",
|
||||
argv[1], sfd);
|
||||
printf("try: nc -v 127.0.0.1 %s && ss -tnp | grep %s\n", argv[1], argv[1]);
|
||||
printf("Ctrl-C to stop.\n");
|
||||
pause();
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/* Experiment 03 — accept() and the truth about TCP chunking + EOF.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 03_accept_recv.c -o 03_accept_recv
|
||||
* Run: ./03_accept_recv 8081
|
||||
*
|
||||
* In another terminal:
|
||||
* nc 127.0.0.1 8081 -> type "hello" + Enter, then more text, watch this
|
||||
* program print one line per recv() with its size
|
||||
* Ctrl-D / Ctrl-C -> watch the final recv() return 0 (EOF)
|
||||
*
|
||||
* Scripted split-line test (same connection, "par" then later "tial\n"):
|
||||
* send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
* { printf 'par'; sleep 1; printf 'tial\n'; } | send 8081
|
||||
*
|
||||
* Lesson: recv() returns whatever bytes are available, not "one message".
|
||||
* A logical line can arrive in pieces; the final 0 is EOF.
|
||||
*/
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct sockaddr_in addr; // for the host configration
|
||||
unsigned char buf[64]; // message size
|
||||
ssize_t n;
|
||||
ssize_t i;
|
||||
int sfd; // socket fd
|
||||
int cfd; //
|
||||
|
||||
if (argc != 2)
|
||||
{
|
||||
fprintf(stderr, "usage: %s PORT\n", argv[0]);
|
||||
return (1);
|
||||
}
|
||||
sfd = socket(AF_INET, SOCK_STREAM, 0); // init the socket fd
|
||||
if (sfd < 0)
|
||||
{
|
||||
perror("socket");
|
||||
return (1);
|
||||
}
|
||||
memset(&addr, 0, sizeof(addr)); // remove the struct data
|
||||
addr.sin_family = AF_INET; // add the configrations
|
||||
addr.sin_addr.s_addr = htonl(2130706433); // add the configrations
|
||||
addr.sin_port = htons(atoi(argv[1])); // add the configrations
|
||||
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0) // use the socket alocate the port
|
||||
{
|
||||
perror("bind");
|
||||
return (1);
|
||||
}
|
||||
if (listen(sfd, 10) < 0) // listn to the network
|
||||
{
|
||||
perror("listen");
|
||||
return (1);
|
||||
}
|
||||
printf("waiting: nc 127.0.0.1 %s\n", argv[1]);
|
||||
cfd = accept(sfd, NULL, NULL); // connection fd when accetp the connection
|
||||
if (cfd < 0)
|
||||
{
|
||||
perror("accept");
|
||||
return (1);
|
||||
}
|
||||
printf("accepted! listening fd = %d, conversation fd = %d (a NEW one)\n",
|
||||
sfd, cfd);
|
||||
while ((n = recv(cfd, buf, sizeof(buf), 0)) > 0) //byte get revived form the connection
|
||||
{
|
||||
printf("recv -> %zd bytes: [", n);
|
||||
i = 0;
|
||||
while (i < n)
|
||||
{
|
||||
if (isprint(buf[i]))
|
||||
printf("%c", buf[i]);
|
||||
else
|
||||
printf(".");
|
||||
i++;
|
||||
}
|
||||
printf("]\n");
|
||||
fflush(stdout);
|
||||
}
|
||||
printf("recv returned %zd <- EOF (peer closed) or error. Bye.\n", n);
|
||||
close(cfd);
|
||||
close(sfd);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/* Experiment 04 — select() with TWO sources: your keyboard (stdin) and a
|
||||
* listening socket. You are watching the waiting room in action.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 04_select_two.c -o 04_select_two
|
||||
* Run: ./04_select_two 8081
|
||||
*
|
||||
* Then, in order:
|
||||
* - type something + Enter here -> "stdin ready"
|
||||
* - nc 127.0.0.1 8081 -> "listener ready", it accepts,
|
||||
* reads one line, closes that client
|
||||
* - Ctrl-D in this terminal -> stdin EOF, program exits
|
||||
*
|
||||
* Lesson: select() blocks until ANY watched fd is ready, then tells you which
|
||||
* one(s) via FD_ISSET. This is the exact heartbeat of mini_serv.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
struct sockaddr_in addr; // socket
|
||||
fd_set rfds; // a set of fds to read
|
||||
char buf[128]; // the buffer
|
||||
ssize_t n;
|
||||
int sfd; // socket fd
|
||||
int cfd; // connection fd
|
||||
int maxfd; // max number of fds
|
||||
|
||||
if (argc != 2)
|
||||
{
|
||||
fprintf(stderr, "usage: %s PORT\n", argv[0]);
|
||||
return (1);
|
||||
}
|
||||
setvbuf(stdout, NULL, _IOLBF, 0);
|
||||
sfd = socket(AF_INET, SOCK_STREAM, 0); //create a stream socket
|
||||
if (sfd < 0)
|
||||
{
|
||||
perror("socket");
|
||||
return (1);
|
||||
}
|
||||
memset(&addr, 0, sizeof(addr));
|
||||
addr.sin_family = AF_INET; // add the configrations
|
||||
addr.sin_addr.s_addr = htonl(2130706433);
|
||||
addr.sin_port = htons(atoi(argv[1]));
|
||||
if (bind(sfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
|
||||
{
|
||||
perror("bind");
|
||||
return (1);
|
||||
}
|
||||
if (listen(sfd, 10) < 0)
|
||||
{
|
||||
perror("listen");
|
||||
return (1);
|
||||
}
|
||||
maxfd = sfd; /* stdin is fd 0, so the highest is the socket */
|
||||
printf("watching stdin(0) and the listener(fd %d). Type here, or nc 127.0.0.1 %s\n",
|
||||
sfd, argv[1]);
|
||||
while (1)
|
||||
{
|
||||
FD_ZERO(&rfds); /* select destroys the set: rebuild every loop */
|
||||
FD_SET(0, &rfds);
|
||||
FD_SET(sfd, &rfds);
|
||||
if (select(maxfd + 1, &rfds, NULL, NULL, NULL) < 0)
|
||||
continue ;
|
||||
if (FD_ISSET(0, &rfds))
|
||||
{
|
||||
n = read(0, buf, sizeof(buf) - 1);
|
||||
if (n <= 0)
|
||||
{
|
||||
printf("stdin EOF — bye.\n");
|
||||
break ;
|
||||
}
|
||||
buf[n] = 0;
|
||||
printf("stdin ready: [%s]", buf);
|
||||
}
|
||||
if (FD_ISSET(sfd, &rfds))
|
||||
{
|
||||
cfd = accept(sfd, NULL, NULL);
|
||||
if (cfd < 0)
|
||||
continue ;
|
||||
printf("listener ready: accepted fd %d — reading one line...\n", cfd);
|
||||
n = recv(cfd, buf, sizeof(buf) - 1, 0);
|
||||
if (n > 0)
|
||||
{
|
||||
buf[n] = 0;
|
||||
printf(" got: [%s]", buf);
|
||||
}
|
||||
else
|
||||
printf(" recv returned %zd (EOF/error)\n", n);
|
||||
close(cfd);
|
||||
}
|
||||
}
|
||||
close(sfd);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
/* Experiment 05 — fd_set is a bitmap. See the bits, then watch select() rewrite them.
|
||||
*
|
||||
* Build: cc -Wall -Wextra -Werror 05_fdset.c -o 05_fdset
|
||||
* Run: ./05_fdset
|
||||
*
|
||||
* Part 1 (pure macros): the set is just bits. FD_ZERO/SET/CLR/ISSET only flip
|
||||
* and read bits — no fd is created, closed, or checked.
|
||||
*
|
||||
* Part 2 (real syscall): two pipes — one with a byte waiting (readable), one
|
||||
* empty (not readable). Both bits go into the set; select() returns with ONLY
|
||||
* the readable one still marked. That is the destructive rewrite that makes
|
||||
* "rebuild or copy the set every loop" mandatory in mini_serv.
|
||||
*
|
||||
* Note: FD_SET(5) in part 1 does not create fd 5. If you pass select() a bit
|
||||
* whose fd is not actually open, select fails with -1 / EBADF. Bits are not fds.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/select.h>
|
||||
#include <sys/time.h>
|
||||
|
||||
static void print16(const char *label, const fd_set *set)
|
||||
{
|
||||
int i;
|
||||
|
||||
printf("%s\n ", label);
|
||||
i = 15;
|
||||
while (i >= 0)
|
||||
{
|
||||
printf("%d", FD_ISSET(i, set) ? 1 : 0);
|
||||
if (i % 8 == 0)
|
||||
printf(" ");
|
||||
i--;
|
||||
}
|
||||
printf(" (bits 15..0)\n");
|
||||
}
|
||||
|
||||
static int max_of(int a, int b)
|
||||
{
|
||||
if (a > b)
|
||||
return (a);
|
||||
return (b);
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
fd_set set;
|
||||
struct timeval tv;
|
||||
int ready[2];
|
||||
int empty[2];
|
||||
int r;
|
||||
|
||||
printf("FD_SETSIZE = %d | sizeof(fd_set) = %zu bytes (%zu bits)\n",
|
||||
FD_SETSIZE, sizeof(fd_set), sizeof(fd_set) * 8);
|
||||
|
||||
/* ---- part 1: the macros are only bit operations ------------------- */
|
||||
FD_ZERO(&set);
|
||||
print16("FD_ZERO(&set):", &set);
|
||||
FD_SET(3, &set);
|
||||
FD_SET(5, &set);
|
||||
print16("after FD_SET(3) + FD_SET(5):", &set);
|
||||
printf("FD_ISSET(3)=%d FD_ISSET(4)=%d FD_ISSET(5)=%d\n",
|
||||
FD_ISSET(3, &set) != 0, FD_ISSET(4, &set) != 0,
|
||||
FD_ISSET(5, &set) != 0);
|
||||
FD_CLR(3, &set);
|
||||
print16("after FD_CLR(3):", &set);
|
||||
|
||||
/* ---- part 2: select() with real file descriptors ------------------ */
|
||||
if (pipe(ready) < 0 || pipe(empty) < 0)
|
||||
{
|
||||
perror("pipe");
|
||||
return (1);
|
||||
}
|
||||
if (write(ready[1], "x", 1) != 1)
|
||||
{
|
||||
perror("write");
|
||||
return (1);
|
||||
}
|
||||
printf("\nreal fds: readable pipe fd=%d (1 byte waiting), silent pipe fd=%d (empty)\n",
|
||||
ready[0], empty[0]);
|
||||
FD_ZERO(&set);
|
||||
FD_SET(ready[0], &set);
|
||||
FD_SET(empty[0], &set);
|
||||
printf("before select: FD_ISSET(readable)=%d FD_ISSET(silent)=%d\n",
|
||||
FD_ISSET(ready[0], &set) != 0, FD_ISSET(empty[0], &set) != 0);
|
||||
tv.tv_sec = 0;
|
||||
tv.tv_usec = 0;
|
||||
r = select(max_of(ready[0], empty[0]) + 1, &set, NULL, NULL, &tv);
|
||||
printf("select returned %d (number of ready fds)\n", r);
|
||||
printf("after select: FD_ISSET(readable)=%d FD_ISSET(silent)=%d <- non-ready bit GONE\n",
|
||||
FD_ISSET(ready[0], &set) != 0, FD_ISSET(empty[0], &set) != 0);
|
||||
|
||||
printf("\nConclusion: select() is an in/out parameter that keeps only ready bits.\n"
|
||||
"mini_serv therefore rebuilds or copies its set before every call.\n");
|
||||
close(ready[0]);
|
||||
close(ready[1]);
|
||||
close(empty[0]);
|
||||
close(empty[1]);
|
||||
return (0);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
# Explore — four tiny programs to make the fundamentals visible
|
||||
|
||||
These are **learning toys**, not exam material. Run them once, understand what you saw,
|
||||
then forget the code (the exam is `mini_serv` only).
|
||||
|
||||
```bash
|
||||
cd explore
|
||||
for n in 01_fds 02_bind_listen 03_accept_recv 04_select_two; do
|
||||
cc -Wall -Wextra -Werror $n.c -o $n && echo "$n built"
|
||||
done
|
||||
```
|
||||
|
||||
Open two or three terminals for the experiments that need `nc`.
|
||||
|
||||
---
|
||||
|
||||
## 01 — fds are small integers, reused
|
||||
|
||||
```bash
|
||||
./01_fds
|
||||
```
|
||||
|
||||
**Look for:** `stdin=0 stdout=1 stderr=2`, then a file and a socket taking `3` and `4`, then
|
||||
the same numbers coming back after `close()`. This is the *whole* idea behind "the array
|
||||
index is the fd".
|
||||
|
||||
## 02 — listen without accept: connections queue in the kernel
|
||||
|
||||
```bash
|
||||
./02_bind_listen 8081 # terminal 1
|
||||
|
||||
# terminal 2:
|
||||
ss -tlnp | grep 8081 # LISTEN, with backlog
|
||||
nc -v 127.0.0.1 8081 # says "succeeded"!
|
||||
ss -tnp | grep 8081 # ESTABLISHED — sitting in the accept queue
|
||||
```
|
||||
|
||||
**Look for:** `nc` succeeding even though the program never called `accept()`. Then `Ctrl-C`
|
||||
the server and run `nc -v` again → **Connection refused** (nobody listening). That pair of
|
||||
observations covers 90% of "why does nc say X" questions.
|
||||
|
||||
## 03 — accept returns a NEW fd; recv gives chunks, not messages
|
||||
|
||||
```bash
|
||||
./03_accept_recv 8081 # terminal 1
|
||||
|
||||
# terminal 2 (interactive):
|
||||
nc 127.0.0.1 8081 # type slowly, then fast; press Enter; watch chunks
|
||||
|
||||
# terminal 2 (scripted split line, same connection):
|
||||
send() { exec 3<>/dev/tcp/127.0.0.1/"$1"; cat >&3; exec 3>&-; }
|
||||
{ printf 'par'; sleep 1; printf 'tial\n'; } | send 8081
|
||||
```
|
||||
|
||||
**Look for:** `listening fd = 3, conversation fd = 4`; the same line arriving in 1, 2 or 3
|
||||
`recv` events; and finally `recv returned 0` when the client goes away (EOF).
|
||||
|
||||
## 04 — select() = "wait for any of these fds"
|
||||
|
||||
```bash
|
||||
./04_select_two 8081 # terminal 1
|
||||
|
||||
# type in terminal 1 -> stdin ready
|
||||
# nc 127.0.0.1 8081 -> listener ready, accepted, one line read
|
||||
# Ctrl-D in terminal 1 -> stdin EOF, exits
|
||||
```
|
||||
|
||||
**Look for:** one `select()` call being woken by *two completely different sources*. That's
|
||||
exactly how the exam server juggles the listening socket and every client at once.
|
||||
|
||||
---
|
||||
|
||||
## 05 — `fd_set` is a bitmap, and `select` rewrites it
|
||||
|
||||
```bash
|
||||
cc -Wall -Wextra -Werror 05_fdset.c -o 05_fdset
|
||||
./05_fdset
|
||||
```
|
||||
|
||||
**Look for:** `FD_SETSIZE = 1024`; the 16-bit picture changing as you `FD_SET`/`FD_CLR`;
|
||||
then two real pipes (one with a byte, one empty) going into a set — after `select`, **only
|
||||
the readable pipe's bit survives**. That last line is the reason mini_serv rebuilds or copies
|
||||
its sets every loop. (Bonus: marking a bit for an fd that isn't open makes `select` fail with
|
||||
`EBADF` — bits are not fds.)
|
||||
|
||||
---
|
||||
|
||||
## After each experiment, write one sentence
|
||||
|
||||
What did I *see* that I didn't believe before? (e.g. "the connection exists before accept",
|
||||
"one line can arrive in pieces", "fds get reused"). Those sentences are worth more than the
|
||||
code. Then go back to `fundamentals.md` §4–§8 and read the matching section — it will feel
|
||||
obvious now.
|
||||
Executable
BIN
Binary file not shown.
Reference in New Issue
Block a user