//
// Created by hlhd on 2020/12/25.
//
#include <arpa/inet.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <errno.h>
#include <strings.h>
#include <signal.h>
const int MAX_BYTES = 4096;
void sig_handler(int sig)
{
printf("signal %d\n", sig);
while (waitpid(-1, NULL, WNOHANG) > 0);
}
int main(int argc, char** argv)
{
struct sigaction sigact;
sigact.sa_flags = SA_RESTART;
sigact.sa_handler = sig_handler;
sigemptyset(&sigact.sa_mask);
sigaction(SIGCHLD, &sigact, NULL);
char buf[MAX_BYTES];
int clntfd;
char IP_buf[INET_ADDRSTRLEN];
struct sockaddr_in server_addr, clnt_addr;
bzero(&clnt_addr, sizeof(clnt_addr));
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(8888);
server_addr.sin_family = AF_INET;
int lstnfd = socket(AF_INET, SOCK_STREAM, 0);
if (bind(lstnfd, (struct sockaddr*)&server_addr,
sizeof(server_addr)) == -1)
{
perror("bind");
exit(errno);
}
listen(lstnfd, 128);
socklen_t addr_len;
int ret;
pid_t pid;
while (1)
{
addr_len = sizeof(clnt_addr);
printf("begin accept\n");
clntfd = accept(lstnfd, (struct sockaddr*)&clnt_addr, &addr_len);
if (clntfd == -1)
{
perror("accept");
exit(-1);
}
pid = fork();
if (pid == 0)
{
close(lstnfd);
printf("accept from IP: %s Port : %d\n",
inet_ntop(AF_INET, &clnt_addr.sin_addr.s_addr,
IP_buf, sizeof(IP_buf)),
ntohs(clnt_addr.sin_port));
while (1)
{
ret = read(clntfd, buf, sizeof(buf));
if (ret == 0)
{
printf("the other size is closed\n");
break;
}
else
{
buf[ret] = '\0';
printf("read buf %s\n", buf);
}
}
close(clntfd);
exit(0);
}
else if (pid > 0)
{
continue;
}
else if (pid == -1) {
perror("fork");
exit(-1);
}
close(clntfd);
}
close(lstnfd);
return 0;
}