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 复制代码
相关推荐
q567315232 分钟前
自动化拨号爬虫体系:虚拟机集群部署与增量管理
运维·爬虫·网络协议·自动化
刘 大 望1 小时前
传输层:UDP/TCP协议
java·网络·网络协议·tcp/ip·udp·信息与通信
禁默1 小时前
第六届机器学习与计算机应用国际学术会议
运维·人工智能·机器学习·自动化
27^×1 小时前
Linux 常用命令速查手册:从入门到实战的高频指令整理
java·大数据·linux
大肥周1 小时前
Linux上解决telnet失败问题
linux
apolloyhl1 小时前
深入理解 Linux 内核进程管理
linux·运维·服务器·操作系统
大聪明-PLUS1 小时前
使用 ftrace 跟踪 Linux 内核
linux·嵌入式·arm·smarc
xx.ii1 小时前
43.shell脚本循环与函数
linux·运维·自动化
Kira Skyler2 小时前
抓虫:unshared后执行命令dump
linux
晨欣2 小时前
Umi-OCR:Windows7和Linux上可免费离线使用的OCR应用!
linux·运维·ocr