2014-12-02 70 views
1

你好我做了這個代碼打開一個套接字,並讓一個線程發送數據,所以插座線程打開插座

int is_valid_fd(int fd) 
{ 
    return fcntl(fd, F_GETFD) != -1 || errno != EBADF; 
} 

int main(int Count, char *Strings[]) 
{ 
    pfd.events = POLLIN; 
    pfd.revents = 0;  
    /*---Create streaming socket---*/ 
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) 
    { 
     perror("Socket"); 
     exit(errno); 
    } 
    /*---Initialize address/port structure---*/ 
    bzero(&self, sizeof(self)); 
    self.sin_family = AF_INET; 
    self.sin_port = htons(MY_PORT); 
    self.sin_addr.s_addr = INADDR_ANY; 
    /*---Assign a port number to the socket---*/ 
    if (bind(sockfd, (struct sockaddr*)&self, sizeof(self)) != 0) 
    { 
     perror("socket--bind"); 
     exit(errno); 
    } 
    /*---Make it a "listening socket"---*/ 
    if (listen(sockfd, 20) != 0) 
    { 
     perror("socket--listen"); 
     exit(errno); 
    } 
     err = pthread_create(&(tid), NULL, &thread_accept, NULL); 
     if (err != 0) 
      printf("\ncan't create thread :[%s]", strerror(err)); 
    /*---Forever... ---*/ 
    while(1){ 
     if(0<poll(&pfd,1,100)){ 
      if(pfd.revents & POLLIN){ 
       run = read(pfd.fd, &t,1); 
      } 
     }   
     if(run){    
      if(is_valid_fd(clientfd))send(clientfd, "12 ",3,0); 

     /*---Close data connection---*/   
     } 
     printf("hejsa\n"); 
     fflush(stdout); 
     sleep(1); 
    } 
    /*---Clean up (should never get here!)---*/ 
    close(sockfd); 
    return 0; 
} 

void* thread_accept(){ 
    while (1){  
     /*---accept a connection (creating a data pipe)---*/ 
     clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen); 
     pfd.fd=clientfd; 
     printf("%s:%d, connected\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); 
     run=1; 
     /*---Echo back anything sent---*/ 
     send(clientfd, buffer, recv(clientfd, buffer, MAXBUF, 0), 0);  
     //close(clientfd); 
    } 
} 

我的問題是的話,那當我關閉套接字連接,程序會關閉而不是僅僅關閉套接字,並保持的printf(「海薩\ n)的

+0

這應該是什麼時候結束?你既沒有打破循環,也沒有從主流返回,也沒有退出流程。 – zoska 2014-12-02 10:50:47

+0

@zoska,它不應該結束 – 2014-12-02 11:28:15

+0

好的,那麼它意味着什麼關閉?經過哪些操作?是否有錯誤消息或者它默默退出? – zoska 2014-12-02 12:25:54

回答

1

我沒有看到你打破while循環? 你也應該使用互斥什麼保護共享數據。

我有一個簡短的例子,做類似的事情(但在dif不同的方式)here

+0

我發現,和我一樣,你沒有仔細閱讀這個問題。 OP不希望while循環結束,但它意外結束。 – zoska 2014-12-02 12:27:16

+0

我在第一個while(1)循環之後插入if語句來修復它。感謝您的回答 – Jacob 2014-12-03 07:57:28