2012-04-27 2 views
0

을 스레드 나는 다음과 같은 코드가 있습니다소켓 및 C

파일이 함수 주와 다른 방법을 가지고 principal.c입니다. 에서

주() :

connectAll(&NUM_THREADS); 
printf("TOTAL clients that to connect %d\n",NUM_THREADS); 

pthread_t thread[NUM_THREADS]; 
pthread_attr_t attr; 

/* Initialize and set thread detached attribute */ 
pthread_attr_init(&attr); 
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); 
paramThread params[NUM_THREADS]; 

    for(t=0;t<NUM_THREADS;t++) 
    { 

    printf("What's IP [%s] to connected now? %d\n",regIPConnected[t].ip,regIPConnected[t].idSocket); 

    params[t].idSocket=regIPConnected[t].idSocket; 
    params[t].idThread=t; 

    rc = pthread_create(&(thread[t]), &attr,conectaThread, &(params[t])); 
    if (rc) 
    { 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
    } 
    }//END FOR 

    /* Free attribute and wait for the other threads */ 
    pthread_attr_destroy(&attr); 

    for(t=0; t<NUM_THREADS; t++) 
    { 
    rc = pthread_join(thread[t], &status); 
    if (rc<0) { 
     printf("ERROR; return code from pthread_join() is %d\n", rc); 
    } 
    printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status); 
    }//END FOR 

    printf("Main: program completed. Exiting.\n"); 
    pthread_exit(NULL); 
} 

void *conectaThread (void *arg){ 

    paramThread* params = (paramThread*) &arg; 

    int idSocket=params->idSocket; 
    long tid=params->idThread; 

    printf("Thread %ld starting...\n",tid); 
    printf ("ID SOCKET THREAD %d\n",idSocket); 
    while (1) /* Run forever */ 
    { 

    int state=readSocket(idSocket,"status\n"); 

... 
} 

paramThread의 구조는 다음과 같습니다

typedef struct 
{ 
    int idSocket; 
    long idThread; 
    void (*pf)(int, long); 
} paramThread; 

그리고이 결과가 실행하는 경우

int openSocketInet (char *servIP,unsigned short servPort) 
{ 
    int optval,statusSocket=0; 
    socklen_t optlen = sizeof(optval); 

    /* Create the socket, using TCP */ 

    socketClient = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); 
    printf("OK/NOK socket %d",socketClient); 
    if (socketClient<0) 
    { 
    switch (errno) 
    { 

     /*differents cases of errno*/ 
     default: 
    perror("socket()"); 
    statusSocket= -1; 
    }//END SWITCH 
    }//END IF 


    /* Check the status for the keepalive option */ 
    if(getsockopt(socketClient, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen) < 0 && statusSocket==0) { 
    statusSocket=checkGET_SETSockOpt(socketClient,1); 
    printf("Error getsockopt() is %d\n",statusSocket); 
    }//END IF 

    printf("SO_KEEPALIVE is %s\n", (optval ? "ON" : "OFF")); 

    int fl = fcntl(socketClient, F_GETFL); 
    fcntl(socketClient, F_SETFL, fl | O_NONBLOCK); 

    /* Set the option active */ 
    optval = 1; //-->TRUE 
    optlen = sizeof(optval); 

    if(setsockopt(socketClient, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen) < 0 && statusSocket==0) { 
    statusSocket=checkGET_SETSockOpt(socketClient,0); 
    printf("Error setsockopt() is %d\n",statusSocket); 
    }//END IF 

    printf("SO_KEEPALIVE set on socket\n"); 

    /* Check the status again */ 
    if(getsockopt(socketClient, SOL_SOCKET, SO_KEEPALIVE, &optval, &optlen) < 0 && statusSocket==0) { 
    statusSocket=checkGET_SETSockOpt(socketClient,1); 
    printf("Error getsockopt() is %d\n",statusSocket); 
    }//END IF 

    printf("SO_KEEPALIVE is %s\n", (optval ? "ON" : "OFF")); 


    if (connect(socketClient, (struct sockaddr *)&addressServer, sizeof(addressServer)) < 0 && statusSocket==0) 
    { 
    switch (errno) 
    { 
     /*diffents cases of errno to connect()*/ 
     default: 
    perror("connect()"); 
    statusSocket= -1; 
    }//END SWITCH 
    }//END IF 

    /* Construct the server address structure */ 
    bzero(&addressServer, sizeof(addressServer)); /* Hay que poner todo a ceros */ 

    addressServer.sin_family = AF_INET;   /* Internet address family */ 
    addressServer.sin_port = htons(servPort); /* puerto en formato de red */ 

    /* dirección IP en formato de red */ 
    int errInetAton=inet_aton(servIP, &addressServer.sin_addr); 
    if (errInetAton<0 && statusSocket==0) 
    { 
    printf("Fail the conversion of IP\n",servIP); 
    perror("inet_aton() Motive"); 
    statusSocket= -1; 
    }//END IF 


    printf("The IP %s to connect with sock %d\n",servIP,socketClient); 

    //To return identify a socket or fail 
    if (statusSocket<0) 
    return statusSocket; 
    else 
    return socketClient; 

} 

socket.c에라는 다른 파일, :

 
socket(): Success --> to sock 3 
SO_KEEPALIVE is OFF 
SO_KEEPALIVE set on socket 
SO_KEEPALIVE is ON 
The IP x.x.x.x to connect with sock 3 
socket(): Illegal seek --> to sock 4 
SO_KEEPALIVE is OFF 
SO_KEEPALIVE set on socket 
SO_KEEPALIVE is ON 
The IP y.y.y.y to connect with sock 4 

는 내가 같은 소켓을


감사를 가진 다른 IP에 연결할 수 있으면 좋겠다, 문제는 다른 것입니다 :

What's IP [x.x.x.x] to connected now? 3 
What's IP [y.y.y.y] to connected now? 4 
What's IP [z.z.z.z] to connected now? 5 


Out for 
Thread 5 starting... 
ID SOCKET THREAD 5 
Method READ! Send to socket id [5] and data is '[status]' 
STATUS THREAD 0 
Thread 5 starting... 
ID SOCKET THREAD 5 
Method READ! Send to socket id [5] and data is '[status]' 
Thread 5 starting... 
ID SOCKET THREAD 5 
Method READ! Send to socket id [5] and data is '[status]' 
STATUS THREAD 0 
Info: (-3.35 dB) 
Method WRITE! Send to socket id [5] and data is '[outlevel 0:50 
]' 
El conector está marcado como no bloqueante y la operación solicitada lo bloquearía. 
Method WRITE! Error send() is 0 
Level modify of Vol 50% 
Info: (-24.13 dB) 
Level modify of Vol 50% 
Info: (-52.60 dB) 
Method WRITE! Send to socket id [5] and data is '[outlevel 0:50 
]' 
El conector está marcado como no bloqueante y la operación solicitada lo bloquearía. 
Method WRITE! Error send() is 0 
Level modify of Vol 50% 
Method READ! Send to socket id [5] and data is '[status]' 
hi0! 
send(): No route to host 
Method READ! Error send() is -1 
STATUS THREAD -1 
Method READ! Send to socket id [5] and data is '[status]' 
# 

그러나 소켓 번호는 3 또는 4해야한다 올바르지 않습니다 다음 코드 : 주에서

()

... 
for(t=0;t<NUM_THREADS;t++) 
    { 

    printf("What's IP [%s] to connected now? %d\n",regIPConnected[t].ip,regIPConnected[t].idSocket); 
,

idSocket = regIPConnected [t] .idSocket;

rc = pthread_create(&(thread[t]), &attr,conectaThread,&idSocket); 
    if (rc) 
    { 
     printf("ERROR; return code from pthread_create() is %d\n", rc); 
    } 
    }//END FOR 

    printf("Out for\n\n!"); 

    /* Free attribute and wait for the other threads */ 
    pthread_attr_destroy(&attr); 

    for(t=0; t<NUM_THREADS; t++) 
    { 
    rc = pthread_join(thread[t], &status); 
    if (rc<0) { 
     printf("ERROR; return code from pthread_join() is %d\n", rc); 
    } 
    printf("Main: completed join with thread %ld having a status of %ld\n",t,(long)status); 
    }//END FOR 

    printf("Main: program completed. Exiting.\n"); 
    pthread_exit(NULL); 

}

다른 코드는 동일하다. 첫 번째 소켓 "3"을 가져 오지 않고 마무리 소켓 5를 얻지 않으시겠습니까? 스레드를 끝내야하는 이유는 무엇입니까?

감사

+12

너무 길어서 읽지 못했습니다 ... – Alnitak

+1

* 어떻게해야 소켓을 만들고 IP의 구성 파일에 선언 한 IP를 연결할 수 있습니까? - 가능합니까? 그 진술을 영어로 바꾸려면? –

+0

죄송합니다. 표현이 잘되지 않습니다. – damlopez

답변

1

봅니다이 줄

printf("OK/NOK socket %d",socketClient); 

을 주석 그리고 당신은 더 얻을 수 있는지 확인합니다.

자세한 내용은 OP에 대한 내 의견을 참조하십시오.

+0

고마워, 나는 그것을 볼 수있는 매개 변수가 잘못 될 수 있다고 생각한다. – damlopez

+0

솔벤트, 고마워 !!! – damlopez

+0

@ user1248467 여러분을 환영합니다. Btw : 당신이 upvote하고 대답을 받아 들일지 모르겠지만 내 대답은 ... ;-) – alk

0

소켓 초기화 함수에서 socketClient를 선언하는 것을 볼 수 없습니다. 그것이 글로벌이라면 뮤텍스 또는 다른 메커니즘을 통해 액세스를 직렬화해야합니다. 일반적

,

socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); 

정상 조건 하에서 실패 할 것이다. 시스템 fd/소켓 할당량을 초과했거나 소켓에 대한 적절한 액세스 동기화가 부족합니다.

또한 언급 한 바와 같이 너무 많은 코드와 너무 적은 컨텍스트.