Hello world/Web server: Difference between revisions

→‎{{header|C}}: simplified code, dropped fork(), serving HTML5 (!)
(omissions)
(→‎{{header|C}}: simplified code, dropped fork(), serving HTML5 (!))
Line 8:
 
=={{header|C}}==
Well, thisThis is, um, slightly longer than what other languages would be.
<lang C>#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <signal.h>
#include <netinet/in.h>
#include <netdb.h>
Line 22 ⟶ 19:
#include <err.h>
 
char canned_responseresponse[] = "HTTP/1.1 200 OK\r\n"
"Content-Type: text/html; charset=UTF-8\r\n\r\n"
"<doctype !html><html><head><title>Goodbye,Bye-bye world!baby bye-bye</title>"
"<style>h1body {font background-size:4cm; color: red; text-shadow: .2cm .2cm#111 black}</style>"
"h1 { font-size:4cm; text-align: center; color: black;"
"</head><body><h1>Goodbye, world!</h1></body></html>\r\n";
" text-shadow: 0 0 2mm red}</style></head>"
"</head><body><h1>Goodbye, world!</h1></body></html>\r\n";
 
int main()
void reap(int x)
{
int one = 1, client_fd;
while(waitpid(-1, 0, WNOHANG) > 0);
struct sockaddr_in svr_addr, cli_addr;
}
socklen_t sin_len;
 
int do_server_stuff()
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
intif one(sock =< 1;0)
if (sock < 0) err(1, "can't open socket");
int client_fd;
socklen_t sin_len;
struct sigaction sac;
char msg_in[4096];
 
if (sock < 0) err(1, "can't open socket");
setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(int));
 
int port = 8080;
struct sockaddr_in svr_addr, cli_addr;
svr_addr.sin_family = AF_INET;
svr_addr.sin_addr.s_addr = INADDR_ANY;
svr_addr.sin_port = htons(port);
 
if (bind(sock, (struct sockaddr *) &svr_addr, sizeof(svr_addr)) == -1) {
close(sock);
Line 56 ⟶ 50:
 
listen(sock, 5);
 
sac.sa_handler = reap;
sigemptyset(&sac.sa_mask);
sac.sa_flags = SA_RESTART;
if (sigaction(SIGCHLD, &sac, 0) == -1)
err(1, "can't install signal handler");
 
while (1) {
client_fd = accept(sock, (struct sockaddr *) &cli_addr, &sin_len);
printf("got connection\n");
 
if (client_fd == -1) {
perror("Can't accept");
continue;
}
if (!fork()) { /* child here */
close(sock);
if (read(client_fd, msg_in, 4096) == -1) {
perror("read failure");
}
write(client_fd, canned_response, sizeof(canned_response) - 1);/*-1:'\0'*/
close(client_fd);
exit(0);
}
 
write(client_fd, canned_responseresponse, sizeof(canned_responseresponse) - 1); /*-1:'\0'*/
printf("got connection\n");
close(client_fd);
}
}
 
int main()
{
do_server_stuff();
return 0;
}</lang>
 
Anonymous user