출처 : http://osr507doc.sco.com/en/netguide/dusockD.socketpairs_codetext.html
socketpair
: read / write 가 가능한 한쌍의 socket 을 open 한다.
예제
Socketpair sample code (UNIX only)
The following example illustrates the use of socketpairs, which are a slight generalization of pipes used for two-way stream communication. Because socketpairs are an extension of pipes, their use resembles that of pipes rather than that of standard UNIX domain sockets. For more information, see ``Socketpairs (UNIX domain only)''.
Note that the header files <sys/socket.h> and <sys/types.h> are required in this program. The constants AF_UNIX and SOCK_STREAM are defined in <sys/socket.h>, which in turn requires the file <sys/types.h> for some of its definitions.
Using Socketpairs
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h>#define DATA1 "In Xanadu, did Kublai Khan . . ." #define DATA2 "A stately pleasure dome decree . . ."
/* * This program creates a pair of connected sockets, then forks and * communicates over them. This is very similar to communication with pipes; * however, socketpairs are two-way communications objects. Therefore, * this program can send messages in both directions. */
main() { int sockets[2], child; char buf[1024];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) { perror("opening stream socket pair"); exit(1); }
if ((child = fork()) == -1) perror("fork"); else if (child) { /* This is the parent. */ close(sockets[0]); if (read(sockets[1], buf, 1024, 0) < 0) perror("reading stream message"); printf("-->%s\n", buf); if (write(sockets[1], DATA2, sizeof(DATA2)) < 0) perror("writing stream message"); close(sockets[1]); } else { /* This is the child. */ close(sockets[1]); if (write(sockets[0], DATA1, sizeof(DATA1)) < 0) perror("writing stream message"); if (read(sockets[0], buf, 1024, 0) < 0) perror("reading stream message"); printf("-->%s\n", buf); close(sockets[0]); }
}
'Programming > Linux_Platform' 카테고리의 다른 글
epoll 에 대한 한국어 설명 (0) | 2015.10.19 |
---|---|
close_on_exec (0) | 2015.10.19 |
linux signals (0) | 2015.10.19 |
linux stand out 을 file 에 logging 하기 (0) | 2015.10.19 |
linux namespace (0) | 2015.10.14 |