Skip to content

Instantly share code, notes, and snippets.

@drmingdrmer
Created October 22, 2014 04:19
Show Gist options
  • Save drmingdrmer/5ef59b3c9977ec2e9a4c to your computer and use it in GitHub Desktop.
Save drmingdrmer/5ef59b3c9977ec2e9a4c to your computer and use it in GitHub Desktop.
break accept() with close()/shutdown()
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
/* gcc -lpthread q.c && ./a.out */
int fd;
void*
worker(void *data)
{
int rc;
usleep( 1000*100 );
rc = close( fd );
/* rc = shutdown( fd, SHUT_RDWR ); */
if ( rc != 0 ) {
printf( "error close:%s\n", strerror( errno ) );
}
}
int
main( int argc, char **argv )
{
int rc;
int cfd;
struct sockaddr_in saddr;
pthread_t tid;
fd = socket( AF_INET, SOCK_STREAM, 0 );
printf( "fd=%d\n", fd );
bzero( &saddr, sizeof( saddr ) );
saddr.sin_family = AF_INET;
saddr.sin_addr.s_addr = htonl( INADDR_ANY );
saddr.sin_port = htons( 8000 );
rc = bind( fd, (struct sockaddr*)&saddr, sizeof(saddr) );
if ( rc != 0 ) {
printf( "error bind:%s\n", strerror( errno ) );
exit( 1 );
}
rc = listen( fd, 128 );
if ( rc != 0 ) {
printf( "error listen:%s\n", strerror( errno ) );
exit( 1 );
}
rc = pthread_create( &tid, NULL, worker, NULL );
if ( 0 != rc ) {
printf( "error pthread_create:%s\n", strerror( errno ) );
exit( 1 );
}
cfd = accept( fd, (struct sockaddr*)NULL, NULL );
printf( "client fd=%d\n", cfd );
printf( "error accept:%s\n", strerror( errno ) );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment