Linux知识点 -- 回调函数类型

Linux知识点 -- 回调函数类型

文章目录


1.

cpp 复制代码
#include <functional>

typedef std::function<void (int, const std::string&, const uint16_t&, const std::string&)> func_t;

static void service(int sock, const std::string &cli_ip,
                    const uint16_t &cli_port, const std::string &thread_name)
{
    // 读取消息:TCP流式套接字可以直接使用read和write接口(recvfrom专用于UDP数据报读取)

    char buffer[1024];
    while (true)
    {
        ssize_t s = read(sock, buffer, sizeof(buffer - 1));
        if (s > 0)
        {
            buffer[s] = 0;
            std::cout << thread_name << "|" <<  cli_ip << ":" << cli_port << "# " << buffer << std::endl;
        }
        else if (s == 0) // 对端关闭连接
        {
            logMessage(NORMAL, "%s:%d shutdown, me too!", cli_ip.c_str(), cli_port);
            break;
        }
        else
        {
            logMessage(ERROR, "read sock error, %d:%s", errno, strerror(errno));
            break;
        }
        write(sock, buffer, strlen(buffer));
    }
    close(sock); // 线程在回调函数中关闭不用的文件描述符
}

int main()
{
	func_t func = service;
	int sock;
    std::string ip;
    uint16_t port;
	std::string name;
	
	//...初始化参数
	
	func(sock, ip, port, name);
	
	return 0;
}

2.

与上面的写法是等价的;

cpp 复制代码
#include <functional>

using func_t = std::function<void (int, const std::string&, const uint16_t&, const std::string&)>;

3.bind绑定参数

见Reactor服务器

cpp 复制代码
相关推荐
清水白石00821 小时前
Python 类定义阶段自动注册子类:从 `__init_subclass__` 到插件系统实战
linux·前端·python
蝶恋舞者21 小时前
DNS 服务器(后续持续更新)
运维·服务器
jiang_changsheng21 小时前
Conda 的默认环境创建优先级。
linux·windows·python
smallerxuan21 小时前
Linux 设备树(Device Tree)概览
linux·设备树·dts
海外数字观察家21 小时前
品未云:泰国华商批发零售一体化 ERP,破解本土软件适配难题|CSDN 技术分享
网络·数据库·人工智能
Mortalbreeze1 天前
深入理解 Linux 线程机制(四):线程同步——条件变量与信号量
linux·运维·服务器·开发语言·c++
测功机之家1 天前
精密传动,可靠测试:杭州索川科技减速机测试台解决方案深度解析
大数据·网络·科技
Huangjin007_1 天前
【Linux 系统篇(一)】入门基础指令详解(一)
linux·服务器
嵌入式小能手1 天前
飞凌嵌入式ElfBoard-i2c与从设备通讯编程示例之i2c设备通信编程示例
linux
mounter6251 天前
现代 Linux 内核中的数据持久化艺术:从回写(Writeback)到多样化写策略
linux·linux kernel·kernel·writeback·writethrough