我用fork创建了一堆children,在每个children中,创建一个UDP端口,通过TCP发回给parent,但是问题是children增加到9个的时候,getsockname()函数返回port num每个孩子 0。
int udp_sockfd;
struct sockaddr_in their_addr, my_addr;
socklen_t slen;//used in getsockname()
if((udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(0);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), sizeof(my_addr.sin_zero));
if(bind(udp_sockfd, (struct sockaddr *)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("bind");
exit(1);
}
getsockname(udp_sockfd,(struct sockaddr*)&my_addr,&slen);
printf("client %d: my port number: %d\n",i,my_addr.sin_port);
当有8个孩子时,结果是正确的