#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>//for fork()
#include <sys/wait.h> // for wait()
int main(int argc, char** argv)
{
int pipe_fds[2]; //size가 2인 int형 배열
pid_t pid;
char buf[1024]; //파일 데이터를 담을 버퍼
int wstatus;
printf("[%d] start of function\n", getpid());
memset(buf, 0, sizeof(buf));//초기화
if (pipe(pipe_fds)) {//파이프 생성 0아닌 값은 에러
perror("pipe()");// 에러 처리
return -1;
}
pid = fork();
if (pid == 0) {
/* child process */
close(pipe_fds[1]); //pipe fork problem 해결책
read(pipe_fds[0], buf, sizeof(buf)); //read
printf("parent said: %s\n"), buf);
close(pipe_fds[0]);//사용한 pipe 닫기
}
else if (pid > 0) {
/* parent process */
close(pipe_fds[0]); //pipe fork problem 해결책
strncpy(buf, "hello child", size(buf) - 1); //buf에 문자열 복사
write(pipe_fds[1], buf, strlen(buf)); //write
close(pipe_fds[1]);//사용한 pipe 닫기
pid = wait(&wstatus); //child process 거두기
}
else {
/* error case */
perror("fork()");
goto err;
}
return 0;
err:
close(pipe_fds[0]);
close(pipe_fds[1]);
return -1;
}
'Computer Science > 시스템 프로그래밍' 카테고리의 다른 글
Named Pipe 사용 예시 (0) | 2022.12.22 |
---|---|
Pipe와 Named Pipe (0) | 2022.12.22 |
IPC란? (0) | 2022.12.22 |