Skip to content

Instantly share code, notes, and snippets.

@MasterAler
Last active February 19, 2020 22:32
Show Gist options
  • Save MasterAler/c57d80a2788aacb548c47a8f9cb68ac9 to your computer and use it in GitHub Desktop.
Save MasterAler/c57d80a2788aacb548c47a8f9cb68ac9 to your computer and use it in GitHub Desktop.
Небольшая задачка на сокеты
#include <sys/socket.h>
#include <sys/un.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
/*! Код без проверок, он примерный, он не важен!!!
*/
int create_socket()
{
int sfd;
struct sockaddr_un my_addr, peer_addr;
// ....
sfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (sfd == -1)
return -1;
memset(&my_addr, 0, sizeof(struct sockaddr_un));
my_addr.sun_family = AF_UNIX;
strncpy(my_addr.sun_path, MY_SOCK_PATH, sizeof(my_addr.sun_path) - 1);
if (bind(sfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr_un)) == -1)
return -1;
if (listen(sfd, LISTEN_BACKLOG) == -1)
return -1;
return sfd;
}
int main()
{
socklen_t peer_addr_size;
struct sockaddr_un peer_addr;
int request_count = 0;
const int thread_count = 4;
int sfd = create_socket();
if (sfd == -1)
return EXIT_FAILURE;
for(int i = 0; i < thread_count; ++i) {
std::thread([request_count, sfd]{
while(true) {
int cfd = accept(sfd, (struct sockaddr *) &peer_addr, &peer_addr_size);
if (cfd == -1)
continue;
++request_count;
char buf[32];
read(cfd, buf, 16);
if (memcmp(buf, "FUBAR", sizeof("FUBAR")) == 0)
write(cfd, "1", 1);
else
write(cfd, "0", 1);
close(cfd);
}
});
}
while (true) {
std::cout << request_count << std::endl;
sleep(0);
}
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment