Dmitry V. Levin | fdfa722 | 2014-09-23 00:14:04 +0000 | [diff] [blame] | 1 | #include <assert.h> |
| 2 | #include <stddef.h> |
Dmitry V. Levin | 552bc3a | 2015-01-14 11:32:38 +0000 | [diff] [blame] | 3 | #include <stdio.h> |
Dmitry V. Levin | fdfa722 | 2014-09-23 00:14:04 +0000 | [diff] [blame] | 4 | #include <string.h> |
| 5 | #include <unistd.h> |
| 6 | #include <sys/wait.h> |
| 7 | #include <sys/socket.h> |
| 8 | #include <netinet/in.h> |
| 9 | #include <arpa/inet.h> |
| 10 | |
| 11 | int main(void) |
| 12 | { |
| 13 | static const char data[] = "data"; |
| 14 | const size_t size = sizeof(data) - 1; |
| 15 | struct sockaddr_in addr; |
| 16 | socklen_t len = sizeof(addr); |
| 17 | pid_t pid; |
| 18 | |
| 19 | memset(&addr, 0, sizeof(addr)); |
| 20 | addr.sin_family = AF_INET; |
| 21 | addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); |
| 22 | |
| 23 | close(0); |
| 24 | close(1); |
| 25 | |
Dmitry V. Levin | 552bc3a | 2015-01-14 11:32:38 +0000 | [diff] [blame] | 26 | if (socket(PF_INET, SOCK_STREAM, 0)) { |
| 27 | perror("socket"); |
| 28 | return 77; |
| 29 | } |
| 30 | if (bind(0, (struct sockaddr *) &addr, len)) { |
| 31 | perror("bind"); |
| 32 | return 77; |
| 33 | } |
Dmitry V. Levin | fdfa722 | 2014-09-23 00:14:04 +0000 | [diff] [blame] | 34 | assert(listen(0, 5) == 0); |
| 35 | |
| 36 | memset(&addr, 0, sizeof(addr)); |
| 37 | assert(getsockname(0, (struct sockaddr *) &addr, &len) == 0); |
| 38 | |
| 39 | assert((pid = fork()) >= 0); |
| 40 | |
| 41 | if (pid) { |
| 42 | char buf[sizeof(data)]; |
| 43 | int status; |
| 44 | |
| 45 | assert(accept(0, (struct sockaddr *) &addr, &len) == 1); |
| 46 | assert(close(0) == 0); |
| 47 | assert(recv(1, buf, sizeof(buf), MSG_WAITALL) == (int) size); |
| 48 | assert(waitpid(pid, &status, 0) == pid); |
| 49 | assert(status == 0); |
| 50 | assert(close(1) == 0); |
| 51 | } else { |
| 52 | assert(close(0) == 0); |
| 53 | assert(socket(PF_INET, SOCK_STREAM, 0) == 0); |
| 54 | assert(connect(0, (struct sockaddr *) &addr, len) == 0); |
| 55 | assert(send(0, data, size, MSG_DONTROUTE) == (int) size); |
| 56 | assert(close(0) == 0); |
| 57 | } |
| 58 | |
| 59 | return 0; |
| 60 | } |