Created
July 31, 2011 09:12
-
-
Save mythosil/1116626 to your computer and use it in GitHub Desktop.
echo server (fork)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <sys/socket.h> | |
#include <sys/types.h> | |
#include <arpa/inet.h> | |
#include <unistd.h> | |
#include <errno.h> | |
using namespace std; | |
int setup_listener() | |
{ | |
const unsigned int port = 1986; | |
const int backlog = -1; | |
int listener; | |
struct sockaddr_in sin; | |
if ( (listener = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) { | |
perror("socket"); | |
exit(1); | |
} | |
memset(&sin, 0, sizeof(struct sockaddr_in)); | |
sin.sin_family = AF_INET; | |
sin.sin_addr.s_addr = htonl(INADDR_ANY); | |
sin.sin_port = htons(port); | |
if (bind(listener, (struct sockaddr*)&sin, sizeof(struct sockaddr)) < 0) { | |
perror("bind"); | |
close(listener); | |
exit(1); | |
} | |
if (listen(listener, backlog) < 0) { | |
perror("listen"); | |
close(listener); | |
exit(1); | |
} | |
return listener; | |
} | |
void run_server(int listener) | |
{ | |
const int bufsize = 1024; | |
int sock; | |
struct sockaddr_in client; | |
socklen_t len; | |
pid_t pid; | |
ssize_t recvlen; | |
char buf[bufsize]; | |
while (1) { | |
if ((sock = accept(listener, (struct sockaddr*)&client, &len)) < 0) { | |
perror("accept"); | |
exit(1); | |
} | |
if ((pid = fork()) == 0) { | |
close(listener); | |
recvlen = recv(sock, buf, bufsize-1, 0); | |
send(sock, buf, recvlen, 0); | |
exit(1); | |
} | |
cout << "pid = " << pid << endl; | |
close(sock); | |
} | |
} | |
int main(int argc, const char* argv[]) | |
{ | |
int listener = setup_listener(); | |
run_server(listener); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment