#include #include #include #include #include #include #include #include #include #include #include int main(int argc, char* argv[]) { int status; int server_sock; int client_sock; int accept_sock; /* Server setup */ sockaddr_in server_sin; server_sin.sin_family = AF_INET; server_sin.sin_addr.s_addr = htonl(INADDR_ANY); server_sin.sin_port = htons(short(8888)); memset(server_sin.sin_zero, 0, sizeof(server_sin.sin_zero)); /* Client Setup */ sockaddr_in client_sin; client_sin.sin_family = AF_INET; client_sin.sin_addr.s_addr = htonl(INADDR_LOOPBACK); client_sin.sin_port = htons(short(8888)); memset(client_sin.sin_zero, 0, sizeof(client_sin.sin_zero)); pid_t pid; if ((pid = fork())==0) { sleep(1); /* Client */ client_sock = socket(AF_INET, SOCK_STREAM, 0); //fcntl(client_sock, F_SETFD, FD_CLOEXEC); // initiate connection status = connect(client_sock, (struct sockaddr *) &client_sin, sizeof(sockaddr)); printf("connect\n"); size_t num; num = write(client_sock, "one\n", 5); sleep(2); close(client_sock); } else { /* Server */ server_sock = socket(AF_INET, SOCK_STREAM, 0); //fcntl(server_sock, F_SETFD, FD_CLOEXEC); status = bind(server_sock, (struct sockaddr *) &server_sin, sizeof(struct sockaddr)); if (status != -1) { status = listen(server_sock, SOMAXCONN); printf("listen %d\n", status); } accept_sock = accept(server_sock, NULL, NULL); printf("accept %d\n", accept_sock); #define BUFSIZE 64 char buf[BUFSIZE]; size_t num; memset(buf, 0, BUFSIZE); sleep(2); if ((status = fcntl(accept_sock, F_GETFL))<0) { printf("fcntl get:%s\n", strerror(errno)); exit(0); } printf("fcntl get %X\n", status); status |= O_NONBLOCK; printf("fcntl set %X\n", status); if (fcntl(accept_sock, F_SETFL, status)==-1) { printf("fcntl set non-blocking:%s\n", strerror(errno)); exit(0); } num = read(accept_sock, buf, BUFSIZE); printf("a:%s\n", buf); memset(buf, 0, BUFSIZE); num = read(accept_sock, buf, BUFSIZE); printf("b:%s\n", buf); if ((status = fcntl(accept_sock, F_GETFL))<0) { printf("fcntl get:%s\n", strerror(errno)); exit(0); } printf("fcntl get %X\n", status); status &= (~(O_NONBLOCK)); printf("fcntl set %X\n", status); if (fcntl(accept_sock, F_SETFL, status)==-1) { printf("fcntl set blocking:%s\n", strerror(errno)); exit(0); } } }