gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:25:44 25 4
gpt4 key购买 nike

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

建立连接后,服务器应为每个新客户端返回一个随机数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com