-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfork_webserver.c
More file actions
97 lines (81 loc) · 2.23 KB
/
fork_webserver.c
File metadata and controls
97 lines (81 loc) · 2.23 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
93
94
95
96
97
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
char webpage[] =
"HTTP/1.1 200 ok\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<!DOCTYPE html>\r\n"
"<html><head><title>fork_webserver</title></head>\r\n"
"<body><center><h1>hi</h1><img src=\"picture.jpeg\"></body></html>\r\n";
void sigchld_handler(int s){
while(waitpid(-1,NULL,WNOHANG)>0);
}
int main(int argc,char *argv[]){
struct sockaddr_in server_addr,client_addr;
socklen_t sin_len = sizeof(client_addr);
int fd_server,fd_client;
char buf[2048];
int fdimg;
int on =1;
fd_server = socket(AF_INET,SOCK_STREAM,0);
if(fd_server <0 ){
perror("socket");
exit(1);
}
setsockopt(fd_server,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(int));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(8080);
if(bind(fd_server,(struct sockaddr *) &server_addr,sizeof(server_addr))==-1){
perror("bind");
close(fd_server);
exit(1);
}
if(listen(fd_server,10) == -1){
perror("listen");
close(fd_server);
exit(1);
}
while(1){
fd_client = accept(fd_server , (struct sockaddr *) &client_addr, &sin_len);
if(fd_client ==-1){
perror("Connection failed.\n");
continue;
}
printf("Got client connection.\n");
sa.sa_handler=sigchld_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags=SA_RESTART;
if(sigaction(SIGCHLD,&sa,NULL)==-1)
{
perror("sigaction");
exit(1);
}
if(!fork()){
close(fd_server);
memset(buf,0,2048);
read(fd_client, buf,2047);
printf("%s\n",buf);
if(!strncmp(buf, "GET /picture.jpeg",16)){
fdimg = open("picture.jpeg",O_RDONLY);
sendfile(fd_client, fdimg,NULL,15000);
close(fdimg);
}
else
write(fd_client, webpage,sizeof(webpage) -1);
close (fd_client);
printf("closing\n");
exit(0);
}
close(fd_client);
}
return 0;
}