linux socket 服务器与客户端多进程通信

来源:互联网 发布:python 模拟登录豆瓣 编辑:程序博客网 时间:2024/09/21 09:17
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <errno.h>#include <unistd.h>#include <sys/wait.h>   //waitpid()#include <arpa/inet.h>  //此函数完成网络地址转换**#include <signal.h>#define BACKLOG 5#define PORT  1122#define IP "192.168.61.112"`````int initScoket( ){    // 创建socket    int sfd = socket(AF_INET, SOCK_STREAM, 0);    if (-1 == sfd)    {        perror("socket");        exit(-1);    }    // 处理端口重用    int optval = 1;    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int));    //初始化 socket 结构    struct sockaddr_in saddr = {0};    saddr.sin_family = AF_INET;    saddr.sin_port = htons(PORT);    saddr.sin_addr.s_addr = INADDR_ANY;//inet_addr(IP);    // 绑定 saddr - sfd    if (-1 == bind(sfd, (struct sockaddr *)(&saddr), sizeof(struct sockaddr)))    {        perror("bind");        exit(-1);    }    // 监听 sfd    if (-1 == listen(sfd, BACKLOG))    {        perror("lister");        exit(-1);    }    return sfd;}void reciprocate(int cfd,  struct sockaddr_in caddr){    char databuf[128] = {'\0'};    int sizer = -1;    int sizes = -1;    char *clientip = inet_ntoa(caddr.sin_addr); //连接的客户端ip    while(1)    {        // 接受数据        memset(databuf, '\0', sizeof(databuf)); //清空buf            if ((sizer = recv(cfd, databuf, sizeof(databuf) - 1, 0)) <= 0)      // if 接收到数据 > seziof(databuf)%s打印将出错 因此-1 保留最后一个为 \0        {            perror("recv");            return ;        }                printf("%s说: %s\n",clientip, databuf);        // 发送数据         if ((sizes = send(cfd, databuf, sizeof(databuf), 0) )<= 0)        {            perror("send");            return ;        }    }}int main(){    //  创建socket    bind    listen    int sfd = initScoket();    struct sockaddr_in caddr = {0};    socklen_t clen = sizeof(struct sockaddr);    int cfd = -1;       char *clientip = NULL;     int clientport = 0;    //int status;    while(1)    {   // 等待客户端连接         cfd = accept(sfd, (struct sockaddr *)(&caddr), &clen);        if (-1 == cfd)        {            perror("accept");            continue;        }        //printf("socket cfd =%d\n", cfd);          clientip = inet_ntoa(caddr.sin_addr);   //连接的客户端ip        clientport = ntohs(caddr.sin_port); //连接的客户端口        printf("%d/%s/上线了\n",clientport, clientip);        pid_t pid = fork();        if (pid < 0)        {            perror("fork");            continue;        }else if (pid == 0)        {            //子进程处理            reciprocate(cfd,caddr);            close(cfd);            close(sfd);            exit(-1);        }        signal(SIGCHLD,SIG_IGN); //处理僵尸进程        //  pid_t wpid = waitpid(-1, NULL, WNOHANG);;   //回收子进程资源 子进程退出了 父进程 在accept()处阻塞 只有 新用户连接才能结束 以前的 僵尸进程 ,还是用信号量处理比较好        close(cfd); // 父进程结束子进程 socket    }    close(sfd);    return 0;}
0 0
原创粉丝点击