0

共有3个进程,一个管理器和两个客户端,管理器通过TCP向两个客户端发送消息,下面的代码是客户端的一部分。当我将所有参数传递给 add_to_ring 函数,并从传递参数的 TCP 套接字开始到 recv() 时。recv() 函数将和两个客户端都收到正确的消息,但后来我发现传递给此函数的参数都已更改,我不知道是谁更改了它们,它们在 recv() 之前是正确的,并且在之后立即更改recv() 之间没有发生任何事情。我也尝试将这些参数分配给函数中的某个变量,并且在 recv() 之后这些变量也发生了变化。谁能看到这是为什么?谢谢!

void add_to_ring(int pid,int s_sockfd,int i,traid_info *traidinfo,tcp_recv recvbytcp,     unsigned identifier, struct sockaddr_in my_addr)
{
    //receive add message from TCP
    printf("client %d:pid is %d,i is %d,nonce is %lu,identifier is %lu,port is  %d\n",i,pid,i,recvbytcp.nonce,identifier,my_addr.sin_port);
    char addmsg[100];
    int apid=pid;
    int as_sockfd=s_sockfd;
    int ai=i;
    tcp_recv arecvbytcp=recvbytcp;
    unsigned long int aidentifier=identifier;
    struct sockaddr_in amy_addr=my_addr;
    if((recv(s_sockfd, addmsg, MAXDATASIZE, 0)) == -1)
    {
        perror("recv1");
        exit(1);
    }
    printf("client %d:pid is %d,i is %d,nonce is %lu,identifier is %lu,port is  %d\n",i,pid,i,recvbytcp.nonce,identifier,my_addr.sin_port);
    printf("client %d:pid is %d,i is %d,nonce is %lu,identifier is %lu,port is %d\n",ai,apid,ai,arecvbytcp.nonce,aidentifier,amy_addr.sin_port);
    //start add to ring
    if(addmsg[0]=='a')
    {
    if(i==1)
    {
        traidinfo->succ_port = recvbytcp.FP;
        traidinfo->succ_identifier = identifier;
        traidinfo->pred_port = recvbytcp.FP;
        traidinfo->pred_identifier = identifier;
        traidinfo->my_port = my_addr.sin_port;
        traidinfo->my_identifier = identifier;
    }
}
    printf("client %d:pid is %d,i is %d,nonce is %lu,identifier is %lu,port is %d\n",ai,apid,ai,arecvbytcp.nonce,aidentifier,amy_addr.sin_port);

    //finished adding,send back my message by TCP
    char msg2man[100];
    data_process(arecvbytcp.nonce, msg2man, apid, amy_addr.sin_port);
    printf("client %d: port is %lu\n",ai,amy_addr.sin_port);
    if(send(as_sockfd, msg2man, MAXDATASIZE, 0) == -1)
    {
        perror("send");
        exit(1);
    }
}
4

2 回答 2

3

addmsg只有100个字节,但你recv最多MAXDATASIZE字节。如果您收到超过 100 个字节apidas_sockfd则将被覆盖。

尝试更改 addmsg 的声明:

char addmsg[MAXDATASIZE];
于 2013-10-23T11:23:26.253 回答
0

除了您可能接收(以及发送)超出数组容量的问题之外,您必须记住 TCP 不承诺接收您要求的所有内容,甚至是完整的消息。

您必须检查收到的金额,如果很少,您必须在附加到缓冲区时再次收到。

于 2013-10-23T11:31:26.917 回答