Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/67.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算在C编程中使用TCP/IP套接字连接到服务器的客户端数_C_Sockets_Tcp - Fatal编程技术网

计算在C编程中使用TCP/IP套接字连接到服务器的客户端数

计算在C编程中使用TCP/IP套接字连接到服务器的客户端数,c,sockets,tcp,C,Sockets,Tcp,在C编程中,我必须统计使用互斥和TCP/IP套接字连接到服务器的客户端数量 这是我的server.c源文件: int numberOfClientsConnected = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int main () { // ... creation, binding and listen ... while (1) { clientSocket = accept(se

在C编程中,我必须统计使用互斥和TCP/IP套接字连接到服务器的客户端数量

这是我的server.c源文件:

int numberOfClientsConnected = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int main ()
{
    // ... creation, binding and listen ...

    while (1) {

        clientSocket = accept(serverSocket, (struct sockaddr*)&newAddress, &addrSize);


        pthread_mutex_lock(&mutex);

        numberOfClientsConnected++;

        pthread_mutex_unlock(&mutex);

        child = fork();

        if (child == 0) {

            close(serverSocket);

            while (1) {
                recv(clientSocket, buffer, 1024, 0);

                if (strcmp(buffer, ":exit") == 0) {
                    printf("%s:%d left\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port));
                    pthread_mutex_lock(&mutex);

                    numberOfClientsConnected--;

                    pthread_mutex_unlock(&mutex);

                    break;
                }
                else {
                    printf("%s:%d wrote: %s\n", inet_ntoa(newAddress.sin_addr), ntohs(newAddress.sin_port), buffer);
                    printf("There are %d client(s) connected\n", numeroDiClientAttualmenteConnessi);
                    // Invio del messaggio
                    send(clientSocket, buffer, strlen(buffer), 0);
                }
            }

        }

    }

    close(clientSocket);

    return 0;
}
正如您在我的屏幕截图中所看到的:

如果我检查从client1连接的客户端数量,它将始终显示me 1;如果我与客户2核对,它将始终显示我2。这是连接的客户端数量,取决于我从哪个客户端发送文本。怎么了?

fork创建了一个新进程,而不是一个新线程。变量不在进程之间共享。您的子进程获取变量的一个副本,并且只看到变量分叉时的值