Fork Concept in TCP
Fork Concept in TCP
bzero(buffer, sizeof(buffer));
int receive = recv(clientSocketFd, buffer, sizeof(buffer), 0);
if (receive < 0){
perror("[-]Error receiving data");
} else {
printf("[+]Server: \t%s\n", buffer);
}
}
and this is some part of my server code
while (1){
clientSockFd = accept(serverSockFd, (struct sockaddr*) &cliAddr, &cliAddrSize);
if (clientSockFd < 0){
perror("[-]Accept failed");
continue;
}
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 1/8
printf("[-]Client %s:%d disconnected.\n",
inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port));
break;
}
close(serverSockFd);
You're doing great so far! Let me explain the `fork()` concept in your TCP server code in the simplest
way, with an analogy and then a step-by-step explanation.
🔧 What is `fork()`?
In simple terms:
`fork()` creates a new copy (child process) of the current running program (parent
process). Now both the parent and child run separately and in parallel.
Instead of the same waiter serving all tables, the restaurant clones a new waiter (via `fork()`)
for each customer.
So each customer gets a personal waiter, and they don't have to wait for others to be served.
In your code:
This allows the server to handle many clients at the same time (concurrently).
2. When a client connects, `accept()` returns a socket (`clientSockFd`) to communicate with that
client.
The server receives messages from the client (`recv()`), responds (`send()`), and exits when
the client sends `"exit"`.
It closes its own copy of the server socket (`close(serverSockFd)`) because it doesn't need to
accept more clients.
💡 How it helps:
Without `fork()`, your server can only talk to one client at a time. With `fork()`, it can serve multiple
clients at once, each with their own child process.
why in server code, there are 2 loops 1 is outer and the other is inner how to implement this
Great observation — the two loops in your server code play two different roles. Let’s break it down
clearly and simply.
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 3/8
c
while (1) {
clientSockFd = accept(...);
...
fork(); // create child process
}
This loop:
if (childPid == 0) {
while (1) {
recv(); // receive from this client
...
send(); // send response back
}
}
This loop:
Runs inside the child process, which was created specifically for one client.
It keeps talking to that one client — receiving messages and replying — until the client sends
`"exit"`.
📊 Visual Explanation:
arduino
Each child gets its own inner loop to keep chatting with its client. The parent just keeps accepting more
clients in the outer loop.
while (1) {
clientSockFd = accept(...); // outer loop: accept new client
Would you like me to write the full code for a simple concurrent echo server using this pattern?
Absolutely! Here's a visual + explanation of your concurrent TCP server with two loops using fork(), in a
simple diagram-style format:
+---------------------------+
| MAIN SERVER PROCESS | ← Accepts new clients
|---------------------------|
| |
| while (1): |
| accept(client) |
| fork() |
| | |
| +---> [Child Process for this client] (↓ Inner loop)
| |
+---------------------------+
arduino
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 5/8
| |-- while(1): recv/send with Client 1
|
|---> Client 2 connects
| |
| +---> fork() --> [Child Process 2]
| |
| |-- while(1): recv/send with Client 2
|
|---> Client 3 connects
| |
| +---> fork() --> [Child Process 3]
| |
| |-- while(1): recv/send with Client 3
🧠 Key Concept:
Without `fork()`, only one client can be served at a time.
With `fork()`, each client gets its own process, and all clients can talk to the server
simultaneously.
Would you like a graphical diagram image (boxes and arrows) for this?
what is
bzero(buffer, sizeof(buffer));
fgets(buffer, MAXLINE, stdin);
buffer[strcspn(buffer, "\n")] = '\0'; // remove newline
Great! Let's break down each line of code in detail and dry run with a clear example.
🔍 What it does:
This sets all bytes in `buffer` to 0 (null).
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 6/8
📚 Equivalent (in modern C):
c
memset(buffer, 0, sizeof(buffer));
🔍 What it does:
It reads a line of input from the user (keyboard) and stores it in `buffer`.
📝 Notes:
It reads until Enter is pressed, or until it hits `MAXLINE - 1` characters.
It includes the newline character `\n` at the end, unless the input is too long.
🔍 What it does:
It removes the newline (`\n`) that `fgets` adds.
💡 How:
`strcspn(buffer, "\n")` finds the index of the first `\n`.
That character is replaced with `'\0'` (end of string), removing the newline.
char buffer[100];
User types:
php-template
hello world<Enter>
Step-by-step:
1. `bzero(buffer, sizeof(buffer));`
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 7/8
`buffer` is now:
`"\0\0\0\0\0\0... (100 times)"` (all nulls)
2. `fgets(buffer, 100, stdin);`
✅ Final result:
`buffer` contains a clean string:
arduino
"hello world"
Would you like me to write a full small C program that shows this in action on the terminal?
Printed using ChatGPT to PDF, powered by PDFCrowd HTML to PDF API. 8/8