多进程
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#define ERR_MSG(msg) do{\
fprintf(stderr, "line:%d\n", __LINE__);\
perror(msg);\
}while(0)
#define IP "192.168.0.153"
#define PORT 8888
int deal_cli_msg(int newfd, struct sockaddr_in cin)
{
char buf[128] = "";
ssize_t res = 0;
while(1)
{
bzero(buf, sizeof(buf));
//接收
res = recv(newfd, buf, sizeof(buf), 0);
if(res < 0)
{
ERR_MSG("recv");
return -1;
}
else if(0 == res)
{
printf("[%s : %d] newfd = %d 客户端下线__%d__\n", \
inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, __LINE__);
break;
}
printf("[%s : %d] newfd = %d : %s__%d__\n", \
inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, buf, __LINE__);
//发送
strcat(buf, "*_*");
if(send(newfd, buf, sizeof(buf), 0) < 0)
{
ERR_MSG("send");
return -1;
}
printf("发送成功\n");
}
return 0;
}
void handler(int sig)
{
while(waitpid(-1, NULL, WNOHANG)>0);
}
int main(int argc, const char *argv[])
{
__sighandler_t s = signal(SIGCHLD, handler);
if(SIG_ERR == s)
{
ERR_MSG("signal");
return -1;
}
int sfd = socket(AF_INET, SOCK_STREAM, 0);
if(sfd < 0)
{
ERR_MSG("socket");
return -1;
}
//允许端口快速被重复使用
int reuse = 1;
if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
{
ERR_MSG("setsockopt");
return -1;
}
printf("允许端口快速重用\n");
//填充服务器的地址信息结构体
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
//绑定--->>>>>>>>>>必须绑定
if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
{
ERR_MSG("bind");
return -1;
}
printf("bind success __%d__\n", __LINE__);
//监听
if(listen(sfd, 128) < 0)
{
ERR_MSG("listen");
return -1;
}
printf("listen success __%d__\n", __LINE__);
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
int newfd = -1;
pid_t cpid = -1;
while(1)
{
//父进程用来负责连接
newfd = accept(sfd, (struct sockaddr*)&cin, &addrlen);
if(newfd < 0)
{
ERR_MSG("accept");
return -1;
}
printf("[%s : %d] newfd = %d 连接成功__%d__\n", \
inet_ntoa(cin.sin_addr), ntohs(cin.sin_port), newfd, __LINE__);
cpid = fork();
if(cpid > 0)
{
close(newfd);
}
else if(0 == cpid)
{
close(sfd);
deal_cli_msg(newfd, cin);
close(newfd);
exit(0);
}
else
{
ERR_MSG("fork");
return -1;
}
}
//关闭文件描述符
close(sfd);
return 0;
}