【C语言】多进程服务器

多进程服务器

多进程服务器

步骤

服务器使用父进程 fork 创建子进程来和客户端进行通信,父进程负责取出连接请求。并且父进程接收子进程退出信号,通过信号处理函数回收子进程

步骤:

1.首先屏蔽子进程退出信号

2.使用socket函数,获取一个socket文件描述符

3.使用setsockopt端口复用

4.使用bind函数允许客户端的哪些ip可以访问服务器

5.使用listen监听客户端连接

6.使用accept从已连接的客户端队列中取出一个文件描述符,与它通信

7.使用fork函数创建一个子进程去与上面的文件描述符通信

代码

c 复制代码
#include "socketwrap.h"
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <arpa/inet.h>

// 信号处理函数
void waitchild(int signo)
{
    pid_t wpid;
    while (1)
    {
        wpid = waitpid(-1, NULL, WNOHANG);
        if (wpid > 0)
        {
            printf("child exit, wpid==[%d]\n", wpid);
        }
        else if (wpid == 0 || wpid == -1)
        {
            break;
        }
    }
}

int main()
{
    // 阻塞SIGCHLD信号
    sigset_t mask;
    sigemptyset(&mask);
    sigaddset(&mask, SIGCHLD);
    sigprocmask(SIG_BLOCK, &mask, NULL);
    int sigbol = 1;

    int sfd = Socket(AF_INET, SOCK_STREAM, 0);

    // 设置端口复用
    int opt = 1;
    setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));

    struct sockaddr_in soaddr;
    bzero(&soaddr, sizeof(soaddr));

    soaddr.sin_family = AF_INET;
    soaddr.sin_port = htons(9999);
    soaddr.sin_addr.s_addr = htonl(INADDR_ANY);

    Bind(sfd, (struct sockaddr *)&soaddr, sizeof(soaddr));

    //监听-listen
	Listen(sfd, 128);

    struct sockaddr_in clientsocket;
    socklen_t clilen;
    
    char sIP[16];

    while (1)
    {
        clilen = sizeof(clientsocket);
        bzero(&clientsocket, clilen);
        
        int cfd = Accept(sfd, (struct sockaddr *)&clientsocket, &clilen);

        /* */
        int pid = fork();
        if (pid == 0)
        {
            // 子进程
            close(sfd);
            char buff[64];
            printf("current pid is [%d],father is [%d]\n", getpid(), getppid());
            while (1)
            {
                memset(buff, 0x00, sizeof(buff));
                int n = Read(cfd, buff, sizeof(buff));
                if (n == 0)
                {
                    return 0;
                }
                else if (n < 0)
                {
                    perror("child read error");
                    return -1;
                }
                printf("child [%d] recv data from [%s:%d]:[%s]\n", getpid(), inet_ntop(AF_INET, &clientsocket.sin_addr.s_addr, sIP, sizeof(sIP)), ntohs(clientsocket.sin_port), buff);
                for (int i = 0; i < n; i++)
                {
                    buff[i] = toupper(buff[i]);
                }
                n = Write(cfd, buff, n);
                if (n <= 0)
                {
                    perror("child write error");
                    return -1;
                }
            }
        }
        else if (pid > 0)
        {
            // 父进程
            close(cfd);

            if (sigbol == 1)
            {
                sigbol = 0;
                // 注册SIGCHLD信号处理函数
                struct sigaction act;
                act.sa_handler = waitchild;
                act.sa_flags = 0;
                sigemptyset(&act.sa_mask);
                sigaction(SIGCHLD, &act, NULL);

                // 解除对SIGCHLD信号的阻塞
                sigprocmask(SIG_UNBLOCK, &mask, NULL);
            }

            continue;
        }
        else
        {
            perror("fork error");
            close(sfd);
            return -1;
        }
    
        
    }

    return 0;
}

最后

推荐一个零声教育学习教程,个人觉得老师讲得不错,分享给大家:[Linux,Nginx,ZeroMQ,MySQL,Redis,
fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,
TCP/IP,协程,DPDK等技术内容,点击立即学习:链接

相关推荐
智者知已应修善业1 小时前
【51单片机用数码管显示流水灯的种类是按钮控制数码管加一和流水灯】2022-6-14
c语言·经验分享·笔记·单片机·嵌入式硬件·51单片机
云资源服务商2 小时前
解锁阿里云日志服务SLS:云时代的日志管理利器
服务器·阿里云·云计算
朱包林3 小时前
day45-nginx复杂跳转与https
linux·运维·服务器·网络·云计算
孞㐑¥4 小时前
Linux之Socket 编程 UDP
linux·服务器·c++·经验分享·笔记·网络协议·udp
柳鲲鹏5 小时前
WINDOWS最快布署WEB服务器:apache2
服务器·前端·windows
黄雪超7 小时前
JVM——函数式语法糖:如何使用Function、Stream来编写函数式程序?
java·开发语言·jvm
ThetaarSofVenice7 小时前
对象的finalization机制Test
java·开发语言·jvm
思则变8 小时前
[Pytest] [Part 2]增加 log功能
开发语言·python·pytest
lijingguang8 小时前
在C#中根据URL下载文件并保存到本地,可以使用以下方法(推荐使用现代异步方式)
开发语言·c#
¥-oriented8 小时前
【C#中路径相关的概念】
开发语言·c#