#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/epoll.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
const int MAX_PROC_NUM = 4;
const int MAX_EVENTS = 128;
const int PORT = 8081;
const int BUF_SIZE = 1024;
const int CLIENT_SIZE = 128;
int g_pids[MAX_PROC_NUM] = {0};
void sig_handler(int signo) {
int i;
for (i = 0; i < MAX_PROC_NUM; i++) {
kill(g_pids[i], SIGKILL);
}
}
int child_procedure(int listenfd) {
struct epoll_event ev;
struct epoll_event events[MAX_EVENTS];
int epfd = 0;
int pid = 0;
char buf[BUF_SIZE];
int cnt = 0;
int i = 0;
pid = getpid();
epfd = epoll_create(CLIENT_SIZE + 1);
if (epfd < 0) {
printf("Create epoll failed\n");
return -1;
}
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = listenfd;
if (epoll_ctl(epfd, EPOLL_CTL_ADD, listenfd, &ev) < 0) {
printf("Add ev failed\n");
return -1;
}
printf("Epoll init finished, process pid: %d\n", pid);
while (1) {
cnt = epoll_wait(epfd, events, MAX_EVENTS, 0);
if (cnt <= 0) {
continue;
}
for (i = 0; i < cnt; i++) {
if (events[i].data.fd == listenfd) {
// 新连接请求
int newfd;
printf("Process %d receive a connection request\n", pid);
newfd = accept(listenfd, NULL, 0);
if (newfd <= 0) {
printf("Process %d accept failed\n", pid);
continue;
}
fcntl(newfd, F_SETFL, fcntl(newfd, F_GETFL, 0) | O_NONBLOCK);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = newfd;
epoll_ctl(epfd, EPOLL_CTL_ADD, newfd, &ev);
} else {
int n = read(events[i].data.fd, buf, BUF_SIZE);
printf("Process %d receive a msg, length %d\n", pid, n);
if (n != 0) {
write(events[i].data.fd, buf, n);
}
close(events[i].data.fd);
epoll_ctl(epfd, EPOLL_CTL_DEL, events[i].data.fd, NULL);
}
}
}
return 0;
}
int main() {
int listenfd = 0;
int i = 0;
struct sockaddr_in servaddr;
// signal(SIGINT, sig_handler);
// signal(SIGTERM, sig_handler);
listenfd = socket(AF_INET, SOCK_STREAM, 0);
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(PORT);
fcntl(listenfd, F_SETFL, fcntl(listenfd, F_GETFL, 0) | O_NONBLOCK);
if (bind(listenfd, (struct sockaddr *)&servaddr, sizeof(struct sockaddr)) == -1) {
printf("bind error\n");
return -1;
}
if (listen(listenfd, CLIENT_SIZE) == -1) {
printf("Listen failed\n");
return -1;
}
for (i = 0; i < MAX_PROC_NUM; i++) {
g_pids[i] = fork();
if (0 == g_pids[i]) {
// 子进程跳出循环
break;
}
}
if (i == MAX_PROC_NUM) {
// 父进程:注册信号,退出时把子进程一起 kill 掉
signal(SIGINT, sig_handler);
signal(SIGTERM, sig_handler);
while (1) {
sleep(100);
}
} else {
// 子进程,进入子进程流程
return child_procedure(listenfd);
}
return 0;
}