linux c tcp多进程并发服务端

#include <stdio.h>
#include <errno.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <strings.h>

void print_error(const char *msg)
{
    perror(msg);
    exit(1);
}

void action(int num)
{
    while(waitpid(0,NULL,WNOHANG) > 0);
}

int main()
{
    int sfd = socket(AF_INET,SOCK_STREAM,0);
    if (sfd == -1)
        print_error("socket");
    struct sockaddr_in serv_addr,clie_addr;
    bzero(&serv_addr,sizeof(serv_addr));
    bzero(&clie_addr,sizeof(clie_addr));

    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(8888);
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    //inet_pton(AF_INET,"106.12.24.223",&serv_addr.sin_addr.s_addr);

    if (bind(sfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1)
        print_error("bind");

    if (listen(sfd,128) == -1)
        print_error("listen");
    struct sigaction sig;
    sig.sa_handler = action;
    sig.sa_flags = 0;
    sigemptyset(&sig.sa_mask);
    
    while(1)
    {
        socklen_t clie_addr_len = sizeof(clie_addr);
        int cfd = accept(sfd,(struct sockaddr *)&clie_addr,&clie_addr_len);
        if (cfd == -1)
        {
            if (errno == EINTR)
                continue;
            else
                print_error("accpet");
        }

        pid_t pid = fork();
        if(pid > 0)
        {
            close(cfd);
            sigaction(SIGCHLD,&sig,NULL);
            //signal(SIGCHLD,action);
        }
        else if(pid == 0)
        {
            close(sfd);
            char buffer[BUFSIZ],ipbuf[BUFSIZ];
            int n,i,port;
            bzero(ipbuf,sizeof(ipbuf));
            inet_ntop(AF_INET,&clie_addr.sin_addr.s_addr,ipbuf,sizeof(ipbuf));
            port = ntohs(clie_addr.sin_port);
            printf("client ip:%s port:%d join\n",ipbuf,port);
            while(1)
            {
                bzero(buffer,sizeof(buffer));
                n = read(cfd,buffer,sizeof(buffer));
                if (n == 0)
                {
                    printf("ip:%s port:%d exit\n",ipbuf,port);
                    break;
                }
                else if(n == -1)
                {
                    break;
                }
                write(cfd,buffer,n);
                printf("ip:%s port:%d\n%s\n",ipbuf,port,buffer);
            }
            close(cfd);
            exit(0);
        }
        else
        {
            close(sfd);
            close(cfd);
            print_error("fork");
        }
    }
    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页