好的,以下是一个使用进程池和UNIX域socket通信的示例代码:
#include <iostream>
#include <vector>
#include <queue>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/wait.h>
class ProcessPool {
public:
ProcessPool(size_t numProcesses) {
for (size_t i = 0; i < numProcesses; ++i) {
int sockets[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) {
std::cerr << "Failed to create socket pair" << std::endl;
exit(1);
}
pid_t pid = fork();
if (pid == -1) {
std::cerr << "Failed to fork process" << std::endl;
exit(1);
} else if (pid == 0) {
// Child process
close(sockets[0]);
handleClientConnection(sockets[1]);
exit(0);
} else {
// Parent process
close(sockets[1]);
processIds.push_back(pid);
workerSockets.push_back(sockets[0]);
}
}
}
~ProcessPool() {
for (pid_t pid : processIds) {
kill(pid, SIGTERM);
}
for (pid_t pid : processIds) {
waitpid(pid, nullptr, 0);
}
}
void sendRequest(const std::string& request) {
if (currentWorker < workerSockets.size()) {
int socket = workerSockets[currentWorker];
send(socket, request.c_str(), request.length(), 0);
++currentWorker;
} else {
std::cerr << "No available worker" << std::endl;
}
}
private:
void handleClientConnection(int socket) {
while (true) {
char buffer[1024];
ssize_t bytesRead = recv(socket, buffer, sizeof(buffer) - 1, 0);
if (bytesRead <= 0) {
break;
}
buffer[bytesRead] = '\0';
std::cout << "Received request: " << buffer << std::endl;
// Handle client request
// ...
}
close(socket);
}
std::vector<pid_t> processIds;
std::vector<int> workerSockets;
size_t currentWorker = 0;
};
int main() {
ProcessPool pool(4);
pool.sendRequest("Request 1");
pool.sendRequest("Request 2");
pool.sendRequest("Request 3");
// Do other work
// ...
return 0;
}
在这个示例中,我们使用socketpair
函数创建了一对UNIX域socket。在父进程中,我们将其中一个socket保存在workerSockets
向量中,并将另一个socket传递给子进程。在子进程中,我们通过调用handleClientConnection
函数来处理与父进程通信的socket连接。在这个函数中,我们通过调用recv
函数接收父进程发送的请求,并在接收到请求后进行处理。在这个示例中,我们只是简单地打印出接收到的请求内容,你可以根据自己的需求来编写处理逻辑。
在main
函数中,我们创建了一个包含4个子进程的进程池pool
。然后,我们使用sendRequest
函数向进程池中的子进程发送请求。在这个示例中,我们发送了3个请求,每个请求都会被发送给一个可用的子进程。你可以根据需要在主进程中发送更多的请求。
希望对你有帮助!