Skip to content

Instantly share code, notes, and snippets.

@infynyxx
Created February 7, 2010 08:09
Show Gist options
  • Save infynyxx/297303 to your computer and use it in GitHub Desktop.
Save infynyxx/297303 to your computer and use it in GitHub Desktop.
Simple preforking server
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
int main(int argc, char *argv[]) {
struct sockaddr_in addr;
int listenSocket, newSocket;
char buffer[25];
int result, i, value, pid, nChildren = 1, nRead;
if (argc > 1) {
nChildren = atoi(argv[1]);
}
listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
value = 1;
result = setsockopt(listenSocket, SOL_SOCKET, SO_REUSEADDR, &value, sizeof(value));
if (result < 0) {
perror("perforking");
return 0;
}
addr.sin_family = AF_INET;
addr.sin_port = htons(1972);
addr.sin_addr.s_addr = INADDR_ANY;
result = bind(listenSocket, (struct sockaddr *) &addr, sizeof(addr));
if (result < 0) {
perror("perforking");
return 0;
}
result = listen(listenSocket, 5);
if (result < 0) {
perror("perforking");
return 0;
}
for (i = 0; i < nChildren; i++) {
if ((pid = fork()) == 0) {
while(1) {
newSocket = accept(listenSocket, NULL, NULL);
printf("Client connected to the child process %i\n", getpid());
nRead = recv(newSocket, buffer, 25, 0);
buffer[nRead] = '\0';
send(newSocket, buffer, nRead, 0);
close(newSocket);
printf("Client disconnected from child process %i\n", getpid());
}
}
}
wait(NULL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment