【发布时间】:2020-02-14 23:53:57
【问题描述】:
所以我有一个服务器,它应该为每个与服务器的新连接创建一个新进程。因此,我将有多个客户端连接到一台服务器。
当建立连接时,服务器应该为每个新客户端返回一个随机数 id。
问题:服务器正在为连接到服务器的所有客户端(终端)打印相同的随机数 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));
}
【问题讨论】:
标签: c sockets ubuntu server fork