为什么recv()改变了不相关的变量

时间:2013-10-23 10:47:41

标签: c tcp recv

总共有3个进程,一个管理器和两个客户端,管理器通过TCP向两个客户端发送消息,下面的代码是客户端的一部分。因为我将所有参数传递给add_to_ring函数,并从TCP套接字开始recv(),该套接字来自传递的参数。 recv()函数将和两个客户端都收到正确的消息,但后来我发现传递给这个函数的参数都被改变了,我不知道是谁更改了它们,它们在recv()之前是正确的并且在之后被更改了recv(),between之间没有任何反应。我也尝试将这些参数分配给函数中的某个变量,并且在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);
    }
}

2 个答案:

答案 0 :(得分:3)

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

尝试更改addmsg的声明:

char addmsg[MAXDATASIZE];

答案 1 :(得分:0)

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

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