-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path34a.c
More file actions
92 lines (77 loc) · 2.44 KB
/
34a.c
File metadata and controls
92 lines (77 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/*
============================================================================
Name : 34a
Author : Piyush Singh
Description : Write a program to create a concurrent server.
a. use fork
b. use pthread_create
Date: 26th Sep, 2025.
============================================================================
*/
// TCP Concurrent Server using fork()
#include <stdio.h> // printf(), perror()
#include <stdlib.h> // exit()
#include <string.h> // memset()
#include <unistd.h> // read(), write(), close(), fork()
#include <sys/socket.h> // socket(), bind(), listen(), accept()
#include <netinet/in.h> // sockaddr_in, htons(), INADDR_ANY
void handle_client(int client_fd)
{
char buffer[1024];
// Read message from client
read(client_fd, buffer, sizeof(buffer));
printf("👶 Child received: %s\n", buffer);
// Send response to client
write(client_fd, "👋 Hello from forked server!", 28);
// Close client socket
close(client_fd);
}
int main()
{
int server_fd, client_fd;
struct sockaddr_in server_addr;
// Step 1: Create TCP socket
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1)
{
perror("❌ socket failed");
exit(1);
}
// Step 2: Bind to port 8081
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY; // Accept connections from any IP
server_addr.sin_port = htons(8081); // Port number
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1)
{
perror("❌ bind failed");
exit(1);
}
// Step 3: Listen for incoming connections
listen(server_fd, 5);
printf("🟢 Fork-based server listening on port 8081...\n");
// Step 4: Accept and handle clients concurrently
while (1)
{
client_fd = accept(server_fd, NULL, NULL);
if (client_fd == -1)
{
perror("❌ accept failed");
continue;
}
// Create a child process to handle the client
if (fork() == 0)
{
handle_client(client_fd);
exit(0); // Child exits after handling
}
// Parent closes duplicate client socket
close(client_fd);
}
return 0;
}
/*
Output:
╰─ ./34a ─╯
🟢 Fork-based server listening on port 8081...
*/