Last active
August 29, 2015 14:01
-
-
Save HugoGuiroux/344b1a885f79c7997bfa to your computer and use it in GitHub Desktop.
Socket non blocking and socket size
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* Author: Hugo Guiroux: http://hugoguiroux.blogspot.fr/ */ | |
| #include <unistd.h> | |
| #include <stdio.h> | |
| #include <sys/types.h> | |
| #include <sys/socket.h> | |
| #include <fcntl.h> | |
| #include <string.h> | |
| #include <errno.h> | |
| int main() | |
| { | |
| /* | |
| * 1. Open socket | |
| * 2. Set non clocking | |
| * 3. do n write up to filling socket | |
| * 4. do 10 read | |
| * 5. fill up to 10 to check it works | |
| * 6. close socket | |
| */ | |
| // 1 | |
| int fds[2]; | |
| if (socketpair(AF_UNIX, SOCK_STREAM, 0, fds) != 0) { | |
| perror("socketpair() failed"); | |
| return -1; | |
| } | |
| // 2 | |
| if (fcntl(fds[0], F_SETFL, O_NONBLOCK) != 0) { | |
| perror("fnctl() failed"); | |
| return -1; | |
| } | |
| // 3 | |
| ssize_t size; | |
| char c = 0; | |
| ssize_t ret; | |
| for (size = 0;; size++) { | |
| ret = write(fds[0], &c, 1); | |
| if (ret != 1) { | |
| printf | |
| ("[expected]: write returning %zd, error = %s(%d)\n", | |
| ret, strerror(errno), errno); | |
| break; | |
| } | |
| } | |
| printf("Found max size of socket is %zd\n", size); | |
| // 4 | |
| for (int i = 0; i < 10; i++) { | |
| if (read(fds[1], &c, 1) != 1) { | |
| perror("read() error"); | |
| return -1; | |
| } | |
| } | |
| // 5 | |
| for (int i = 0; i < 10; i++) { | |
| if (write(fds[0], &c, 1) != 1) { | |
| perror("write() error"); | |
| return -1; | |
| } | |
| } | |
| ret = write(fds[0], &c, 1); | |
| if (ret == 1) { | |
| printf | |
| ("error while filling up again the socket, no error was raised !\n"); | |
| return -1; | |
| } | |
| // 6 | |
| close(fds[0]); | |
| close(fds[1]); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment