728x90
반응형
[IPC] name pipe 예제 코드
1. 구조
- 단방향 통신 구조이며 한쪽에서 쓰면 다른 한쪽에서 읽을 수 있는 구조로 되어있다.
- 자세한 설명은 다음 포스트 참조
[프로세스간 통신] IPC(inter process communication) 종류
2. 예제 코드
1) Client(Writer)
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define MSG_SIZE 80
#define PIPENAME "./named_pipe_file"
int main(void) {
char msg[MSG_SIZE];
int fd;
int nread, i;
/* named pipe 열기, Write 전용으로 열기 */
if ((fd = open(PIPENAME, O_WRONLY)) < 0) {
printf("fail to open named pipe\n");
return 0;
}
/* Data를 보낸다. */
for (i = 0; i < 3; i++) {
snprintf(msg, sizeof(msg), "Send Message[%i]", i);
if ((nread = write(fd, msg, sizeof(msg))) < 0 ) {
printf("fail to call write()\n");
return 0;
}
}
return 0;
}
2) Server(reader)
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#define MSG_SIZE 80
#define PIPENAME "./named_pipe_file"
int main(void) {
char msg[MSG_SIZE];
int fd;
int nread, rc;
/* 기존에 named pipe가 있으면 삭제 */
if (access(PIPENAME,F_OK) == 0) {
unlink(PIPENAME);
}
/* named pipe 생성하기 */
if ((rc = mkfifo(PIPENAME,0666)) < 0) {
printf("fail to make named pipe\n");
return 0;
}
/* named pipe 열기, Read Write가능 해야 한다 */
if ((fd = open(PIPENAME, O_RDWR)) < 0) {
printf("fail to open named pipe\n");
return 0;
}
while (1) {
if ((nread = read(fd, msg, sizeof(msg))) < 0 ) {
printf("fail to call read()\n");
return 0;
}
printf("recv: %s\n", msg);
}
return 0;
}
728x90
반응형
'프로그래밍 > ExampleCode.com' 카테고리의 다른 글
| [IPC] shared memory 예제 코드 (5) | 2018.09.20 |
|---|---|
| [IPC] pipe 예제 코드 (0) | 2018.09.20 |
| [IPC] message queue 예제 코드 (0) | 2018.09.20 |
| [IPC] 메모리 맵 mmap() 예제 코드 (0) | 2018.09.20 |
| [fseek] 파일 포인터이동 예제 (0) | 2018.08.27 |