套接字没有收到消息AF_UNIX

时间:2013-11-24 16:28:53

标签: c linux shell sockets unix

       Server Side:
 void getMessage(int aSock){
            int n=0;
            char recvline[1025];
            if ( (n = read(aSock, recvline, 1025) ) <0 ) {
                perror("Erro: Nao recebida Mensagem do Servidor");

                printf("%s",recvline);
            }
        }


    .
    .
    .  ( MAIN FUNCTION with all the sockets declarations etc( Its working )

        for(;;){

            clilen = sizeof(cli_addr);
            mysock=accept(serverSocket,(struct sockaddr *) &cli_addr, &clilen);

            if(mysock== -1) { 
                perror(" Falhou a Ligacao "); 
            }
            else {
                if ( (childpid = fork()) < 0 ) {
                    system ("clear");  
                    printf("\t\tServidor: Erro");
                    exit(0);          
                }           
                else if ( childpid == 0 ) {
                    close(serverSocket);        
                    getMessage(mysock); 
                    exit(0);

                }
            }
            close(mysock);
        }
    }
    .
    .

CLIENT SIDE

void socketSender(int idAcont, int aClientId,char aProdnome,int numRestock){
    char buffer[1024];
    int tamanho;
    sprintf(buffer,"%d %d %c %d",idAcont,aClientId,aProdnome,numRestock);
    int sockfd, servlen;
    struct sockaddr_un serv_addr;
    if ((sockfd= socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
        perror("erro ao criar socket cliente");
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sun_family = AF_UNIX;
    strcpy(serv_addr.sun_path, UNIXSTR_PATH);
    servlen = strlen(serv_addr.sun_path) + sizeof(serv_addr.sun_family);
    if (connect(sockfd, (struct sockaddr *) &serv_addr, servlen) < 0)
        perror("erro ao fazer connect no cliente");

    tamanho=strlen(buffer)+1;
    if(write(sockfd,buffer,tamanho)!=tamanho)
        perror("Erro ao escrever no cliente");
    close(sockfd);
}

服务器端一直在等待for(;;)中的消息,它创建了mysocket,它应该从socketsender()获取来自客户端的消息,但消息不会弹出:/任何想法有什么问题?提前谢谢你

1 个答案:

答案 0 :(得分:0)

您确定fork()已关闭服务器进程不仅仅是结束吗?

您的服务器的日志记录代码似乎放错了位置。不应该这样:

if ((n = read(aSock, recvline, 1025) ) <0 ) {
  perror("Erro: Nao recebida Mensagem do Servidor");
  printf("%s",recvline);
}

是:

if ( (n = read(aSock, recvline, 1025) ) <0 ) {
  perror("Erro: Nao recebida Mensagem do Servidor");
}
printf("%s",recvline);