线程打开套接字

时间:2014-12-02 09:35:38

标签: c sockets pthreads

你好我做了这个代码来打开一个套接字并创建一个线程来发送数据,所以socket

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(“hejsa \ n)

1 个答案:

答案 0 :(得分:1)

我看不到你打破while循环的位置? 您还应该使用互斥锁等保护您的共享数据。

我有一个简短的例子,它做了类似的事情(但以不同的方式)here