Dispatch upon receipt in C

I made a piece of code in that there are several threads on my server

The problem is that it is not sending data, but im receiving a different socket.

therefore, if I send something from client 1 to client 2, client2 will receive it only if he sends something (jumps from the recv function) .. how can I solve this?

 /* Thread*/
while (! stop_received) {
        nr_bytes_recv = recv(s, buffer, BUFFSIZE, 0);

        if(strncmp(buffer, "SEND", 4) == 0) {
            char *message = "Text asads \n";
            rv = send(users[0].s, message, strlen(message), 0);
            rv = send(users[1].s, message, strlen(message), 0);
            if (rv < 0) {
                perror("Error sending");
                exit(EXIT_FAILURE);
            }           
        }else{
            char *message = "Unknown command \n";
            rv = send(s, message, strlen(message), 0);
            if (rv < 0) {
                perror("Error sending");
                exit(EXIT_FAILURE);
            }
        }
}
+3
source share
6 answers

To be more specific, there are several types of I / O. What you are currently doing is called I / O blocking. In general, this means that the call sendor recvoperation will be "blocked" so long as it is complete.

i/o. i/o , . / select.

, Select Tutorial. .

, - .

+7

recv(). , select().

+2

.

+1

, perror() ( POSIX), , POSIX, GNU/Linux.

select() , poll() POSIX-, epoll() - Linux. GNU/Linux, select() :

  • poll(),
  • epoll(), .

, , poll() epoll(). , select(), , , .

, , poll() epoll() select().

. epoll() Linux 2.5 (-), .

+1

, .

- :

 /* 1st Thread*/
while (! stop_received) {
        nr_bytes_recv = recv(s, buffer, BUFFSIZE, 0);
}


 /* 2nd Thread*/
while (! stop_received) {
        if(strncmp(buffer, "SEND", 4) == 0) {
            char *message = "Text asads \n";
            rv = send(users[0].s, message, strlen(message), 0);
            rv = send(users[1].s, message, strlen(message), 0);
            if (rv < 0) {
                perror("Error sending");
                exit(EXIT_FAILURE);
            }           
        }else{
            char *message = "Unknown command \n";
            rv = send(s, message, strlen(message), 0);
            if (rv < 0) {
                perror("Error sending");
                exit(EXIT_FAILURE);
            }
        }
}

concurrency , buffer.

0

:

1.) . , , . - concurrency ( pcent). , , , , cpu hog.

2.) Another way is to use the select () function, which allows you to simultaneously control several sockets of different types. for a more detailed description of "select ()" you can use it. :)

0
source

Source: https://habr.com/ru/post/1747830/


All Articles