在新的客户端连接到服务器后尝试fork()[套接字编程C] [英] Trying to fork() after new client connection to server [Socket Programming C]

查看:102
本文介绍了在新的客户端连接到服务器后尝试fork()[套接字编程C]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So I have a server that is supposed to create a new process for every new connection to the server. Therefore I will have multiple clients connecting to one server.

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

When a connection is made the server should return a random number id for each new client.

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

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

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'函数使用隐藏的'state'生成下一个随机数.由于父母从未使用过兰德,所以每个分叉的孩子将获得相同的状态,并将生成相同的随机数序列.

The 'rand' function uses a hidden 'state' to generate the next random number. Since the parent never uses rand, each forked child will get the same state, and will generate the same sequence of random number.

一些可能的解决方法:

  • 在父级中向rand发出一个呼叫(在分叉之前).这将导致每个孩子从不同的状态开始.
  • 在分叉之前在父级中调用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) ;

这篇关于在新的客户端连接到服务器后尝试fork()[套接字编程C]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆