c - 在新的客户端连接到服务器后尝试 fork() [Socket 编程 C]

标签 c sockets ubuntu server fork

所以我有一个服务器,它应该为服务器的每个新连接创建一个新进程。因此,我将有多个客户端连接到一台服务器。

建立连接后,服务器应为每个新客户端返回一个随机数 ID。

问题:服务器正在为连接到服务器的所有客户端(终端)打印相同的随机数 ID。

应该发生什么:子进程应该为新的唯一客户端连接生成 (rand()) id。证明每个新客户端都已连接到服务器。我的 fork 正确吗?

while (1)
{
    pid_t childpid; /* variable to store child's process id */

    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);

    if ((childpid = fork()) == -1)
    { // fork failed.
        close(new_fd);
        continue;
    }
    else if (childpid > 0)
    { // parent process
        printf("\n parent process\n");
    }
    else if (childpid == 0)
    { // child process
        printf("\n child process\n");

        printf("\n random num: %d\n", rand());    -----> Testing, should be unique for each client (its not!)

        /* ***Server-Client Connected*** */
        client_t client = generate_client();

    }
    printf("server: got connection from %s\n",
           inet_ntoa(their_addr.sin_addr));
}

最佳答案

“rand”函数使用隐藏的“状态”来生成下一个随机数。由于父级从不使用 rand,因此每个 fork 的子级将获得相同的状态,并将生成相同的随机数序列。

一些可能的修复:

  • 在父级中对 rand 进行一次调用(在 fork 之前)。这将导致每个 child 从不同的状态开始。
  • 在 fork 之前在父级中调用 rand,并保存 id 供子级使用。
  • 使用 srand 为每个子项设置随机查看。
    int child_id = rand() ;
    if ((childpid = fork()) == -1)
    { // fork failed.
        close(new_fd);
        continue;
    }
    ... Later in the child.
        printf("random num: %d", child_id) ;

关于c - 在新的客户端连接到服务器后尝试 fork() [Socket 编程 C],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58443143/

相关文章:

java - 套接字编程 java - 套接字连接存活了多长时间?我该如何控制它?

c - 用指针在 C 中包装字符串

c - C : warning: assignment from incompatible pointer type [-Wincompatible-pointer-types] 中的函数指针

套接字(Websockets)、端口和协议(protocol)

c# - php与c#的tcp通信问题

PHP 5.6 Mcrypt x64 和 MIT 方案不兼容?

c - 用 C 语言拥有一个非常大的数据结构是一个很好的实践吗

c - 当我尝试在结构体数组中给出值时,为什么我的程序会停止?

php - 为什么从浏览器启动的 php 脚本只执行一个?

MySQL 无法在 Ubuntu 11.04 上安装