linux ipc (socket)
linux application ipc를 socket를 활용해서 제작..
서버는 소켓을 열고 받은걸 바로 다시 보내는 형태로 제작
클라이언트는 연결된 소켓을 사용해서 보내고 받는걸 처리 (read에서 계속 대기 하는 형태입니다.)
server.c
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/socket.h>
- #include <sys/un.h>
- #include
- #include
- #include
- #include
- #define MAXLINE 1024
- int main(int argc, char **argv)
- {
- int server_sockfd, client_sockfd;
- int state, client_len;
- pid_t pid;
- struct sockaddr_un clientaddr, serveraddr;
- char buf[MAXLINE];
- if (argc != 2)
- {
- printf(“Usage : %s [socket file name]\n”, argv[0]);
- printf(“예 : %s /tmp/mysocket\n”, argv[0]);
- exit(0);
- }
- if (access(argv[1], F_OK) == 0)
- {
- unlink(argv[1]);
- }
- client_len = sizeof(clientaddr);
- if ((server_sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
- {
- perror(“socket error : “);
- exit(0);
- }
- bzero(&serveraddr, sizeof(serveraddr));
- serveraddr.sun_family = AF_UNIX;
- strcpy(serveraddr.sun_path, argv[1]);
- state = bind(server_sockfd , (struct sockaddr *)&serveraddr,
- sizeof(serveraddr));
- if (state == -1)
- {
- perror(“bind error : “);
- exit(0);
- }
- state = listen(server_sockfd, 5);
- if (state == -1)
- {
- perror(“listen error : “);
- exit(0);
- }
- while(1)
- {
- client_sockfd = accept(server_sockfd, (struct sockaddr *)&clientaddr, &client_len);
- pid = fork();
- if (pid == 0)
- {
- if (client_sockfd == -1)
- {
- perror(“Accept error : “);
- exit(0);
- }
- while(1)
- {
- memset(buf, 0x00, MAXLINE);
- if (read(client_sockfd, buf, MAXLINE) <= 0)
- {
- close(client_sockfd);
- exit(0);
- }
- printf(“receivd > %s “,buf);
- write(client_sockfd, buf, strlen(buf));
- printf(“send > %s “, buf);
- }
- }
- }
- close(client_sockfd);
- }
client.c
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <sys/socket.h>
- #include
- #include <sys/un.h>
- #include
- #include
- #include
- #define MAXLINE 1024
- int main(int argc, char **argv)
- {
- int client_len;
- int client_sockfd; char buf_in[MAXLINE];
- char buf_get[MAXLINE];
- struct sockaddr_un clientaddr;
- if (argc != 2)
- {
- printf(“Usage : %s [file_name]\n”, argv[0]);
- printf(“예 : %s /tmp/mysocket\n”, argv[0]);
- exit(0);
- }
- client_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
- if (client_sockfd == -1)
- {
- perror(“error : “);
- exit(0);
- }
- bzero(&clientaddr, sizeof(clientaddr));
- clientaddr.sun_family = AF_UNIX;
- strcpy(clientaddr.sun_path, argv[1]);
- client_len = sizeof(clientaddr);
- if (connect(client_sockfd, (struct sockaddr *)&clientaddr, client_len) < 0)
- {
- perror(“Connect error: “);
- exit(0);
- }
- while(1)
- {
- memset(buf_in, 0x00, MAXLINE);
- memset(buf_get, 0x00, MAXLINE);
- printf(“> “);
- fgets(buf_in, MAXLINE, stdin);
- write(client_sockfd, buf_in, strlen(buf_in));
- read(client_sockfd, buf_get, MAXLINE);
- printf(“-> %s”, buf_get);
- }
- close(client_sockfd);
- exit(0);
- }
ref : https://www.joinc.co.kr/w/Site/system_programing/Book_LSP/ch08_IPC