Question

when the program goes to sleepsleep (1)in a thread function ,it suddenly ends. Does it have something to do with thread?

void send_packet(int sockfd, struct sockaddr_in dest_addr)
{   
int packetsize;
while( nsend < MAX_NO_PACKETS)
{      
    printf("send %d\n", nsend);
    nsend++;
    packetsize=pack(nsend); 
    if( sendto(sockfd,sendpacket,packetsize,0,(struct sockaddr *)&dest_addr,sizeof(dest_addr) )<0  )
    {       
        perror("sendto error");
        continue;
    }
    printf(" %d\n", packetsize);
    sleep(1); 
}
}

int find_host(void * arg)
{

send_packet(sockfd, present_addr);
recv_packet(sockfd, recvpacket, from);

pthread_create(&ntid, NULL, find_host, (void *)&inaddr);    
Was it helpful?

Solution

In one comment you write that your main thread ends. Taken from the pthread_create man page:

The new thread terminates in one of the following ways:
[...]
* Any of the threads in the process calls exit(3), or the main thread performs a return from main(). This causes the termination of all threads in the process.

Your main thread needs to pthread_join to wait for the sender to terminate.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top