【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等技术内容,点击立即学习:链接

相关推荐
君顾122 分钟前
西安 24 小时自助健身房系统开发实战指南
java·开发语言·健身房
白色的北极熊28 分钟前
c语言 scanf 输入流有空格,逗号 说明
c语言
Logic10142 分钟前
C语言/数据结构位运算题解:异或XOR找出货船中的“独特载货量“——只出现一次的数字
c语言·数据结构·数组·位运算·时间复杂度·算法题·异或性质
小羊没烦恼!1 小时前
Memory 记忆设计讨论:Agent Memory 的数据模型可以怎么设计
java·开发语言·前端·c++·c#
程序猿编码1 小时前
两张 3090 扛 27B:Qwen3.8-27B 大模型 DFlash2 加速版生产级落地
开发语言·gpt·深度学习·神经网络·大模型·qwen
welfare9621 小时前
新号别搞:内存管理+模板初阶+STL简介
开发语言·c++
敲代码的瓦龙2 小时前
Jetpack?ViewModel!!!
android·开发语言·kotlin·android-studio
白远山2 小时前
智慧场馆解决方案软件开发实战:从架构设计到落地部署指南
java·开发语言·架构·需求分析
IT笔记2 小时前
Rust 迭代器多级链式调用执行顺序笔记
开发语言·笔记·rust
雪落漂泊2 小时前
C++11(上)
开发语言·c++