본문 바로가기

Computer Science/시스템프로그래밍2

IPC 기법 실습1 -pipe

Pipe : 단방향 통신 (부모->자식)

프로세스를 fork()하여 자식프로세스를 만들어 부모에서 자식으로만 보낼 수 있다

1. 부모프로세스에서 fd[1]에 입력할 메세지를 write() 시스템콜을 사용해서 입력

2. 자식프로세스에서는 fd[0], 공란 buf에  read() 시스템콜을 이용하여 읽어서 메세지를 받음

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MSGSIZE 255

char* msg="Hello Child Process!";
int main(){
	char buf[255];
	int fd[2], pid, nbytes;
	if (pipe(fd)<0)
		exit(1);
	pid=fork();
	if (pid>0){
		printf("parent PID:%d, child PID:%d\n",getpid(), pid);
		write(fd[1], msg, MSGSIZE);
		exit(0);
	}
	else{
		printf("child PID:%d\n", getpid());
		nbytes=read(fd[0],buf,MSGSIZE);
		printf("%d, %s\n",nbytes,buf);
		exit(0);
	}
	return 0;
}