Created
April 16, 2015 06:06
-
-
Save cynron/64032820f751e4f8b0a0 to your computer and use it in GitHub Desktop.
pipe_create
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
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <stdarg.h> | |
| #include <string.h> | |
| #include <assert.h> | |
| #include <time.h> | |
| #ifdef _WIN32 | |
| #include <windows.h> | |
| typedef SOCKET pc_socket_t; | |
| #define pc_close_socket(s) closesocket(s) | |
| #define pc_invalid_socket INVALID_SOCKET | |
| #else | |
| #include <unistd.h> | |
| #include <sys/socket.h> | |
| #include <sys/types.h> | |
| #include <netinet/in.h> | |
| typedef int pc_socket_t; | |
| #define pc_close_socket(s) close(s) | |
| #define pc_invalid_socket (-1) | |
| #endif | |
| int pc_pipe_create(pc_socket_t p[2]) | |
| { | |
| struct sockaddr_in addr = { 0 }; | |
| int addr_len = sizeof(struct sockaddr_in); | |
| pc_socket_t listener = pc_invalid_socket; | |
| if (!p) { | |
| return -1; | |
| } | |
| p[0] = pc_invalid_socket; | |
| p[1] = pc_invalid_socket; | |
| if ((listener = socket(AF_INET, SOCK_STREAM, 0)) == pc_invalid_socket) { | |
| return -1; | |
| } | |
| addr.sin_family = AF_INET; | |
| addr.sin_addr.s_addr = htonl(INADDR_ANY); | |
| addr.sin_port = htons(0); | |
| if (bind(listener, (struct sockaddr *)&addr, addr_len)) { | |
| goto fail; | |
| } | |
| if (listen(listener, 1)) { | |
| goto fail; | |
| } | |
| if (getsockname(listener, (struct sockaddr *)&addr, &addr_len)) { | |
| goto fail; | |
| } | |
| assert(sizeof(struct sockaddr_in) == addr_len); | |
| if ((p[0] = socket(AF_INET, SOCK_STREAM, 0)) == pc_invalid_socket) { | |
| goto fail; | |
| } | |
| if (connect(p[0], (struct sockaddr *)&addr, addr_len)) { | |
| goto fail; | |
| } | |
| if ((p[1] = accept(listener, 0, 0)) == pc_invalid_socket) { | |
| goto fail; | |
| } | |
| pc_close_socket(listener); | |
| return 0; | |
| fail: | |
| pc_close_socket(listener); | |
| if (p[0] != pc_invalid_socket) { | |
| pc_close_socket(p[0]); | |
| p[0] = pc_invalid_socket; | |
| } | |
| if (p[1] != pc_invalid_socket) { | |
| pc_close_socket(p[1]); | |
| p[1] = pc_invalid_socket; | |
| } | |
| return -1; | |
| } | |
| int main() | |
| { | |
| pc_socket_t x[2]; | |
| int ret; | |
| int y = 99; | |
| int l; | |
| ret = pc_pipe_create(x); | |
| printf("ret: %d\n", ret); | |
| send(x[0], &y, sizeof(y), 0); | |
| recv(x[1], &l, sizeof(l), 0); | |
| printf("y: %d\n", y); | |
| printf("l: %d\n", l); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment