Skip to content

Instantly share code, notes, and snippets.

@tiancaiamao
Created December 9, 2014 06:14
Show Gist options
  • Save tiancaiamao/0a05662d09e29887f839 to your computer and use it in GitHub Desktop.
Save tiancaiamao/0a05662d09e29887f839 to your computer and use it in GitHub Desktop.
单进程架构
#include <stdio.h>
#include <sys/socket.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
int child(int, int);
int
main() {
int fd;
struct sockaddr_in addr;
int succ;
int i;
fd = socket(AF_INET, SOCK_STREAM, 0);
if (fd == -1) {
perror("socket");
goto err_out;
}
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = htons(9997);
succ = bind(fd, (struct sockaddr*)&addr, sizeof(addr));
if (succ != 0) {
perror("bind");
goto closesock;
}
succ = listen(fd, 5);
if (succ != 0) {
perror("listen");
goto closesock;
}
for (i=0; i<5; i++) {
succ = fork();
if (succ < 0) {
perror("fork");
goto closesock;
} else if (succ == 0) {
// parent process
continue;
} else {
// child process
return child(i, fd);
}
}
return 0;
closesock:
close(fd);
err_out:
return -1;
}
int
child(int idx, int serverfd) {
int fd;
struct sockaddr_in addr;
socklen_t len;
char addrName[INET_ADDRSTRLEN];
const char *addrP;
char buf[] = "hello";
while(1) {
len = sizeof(addr);
fd = accept(serverfd, (struct sockaddr*)&addr, &len);
if (fd < 0) {
perror("accept");
return -1;
}
addrP = inet_ntop(AF_INET, &addr, (char*)addrName, len);
printf("%d accept a connect: %s\n", idx, addrP);
write(fd, buf, strlen(buf));
close(fd);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment