Skip to content

Instantly share code, notes, and snippets.

@Park-Developer
Last active February 6, 2022 06:24
Show Gist options
  • Save Park-Developer/daed5c9e100f4dcd8ba42061c49f79fb to your computer and use it in GitHub Desktop.
Save Park-Developer/daed5c9e100f4dcd8ba42061c49f79fb to your computer and use it in GitHub Desktop.
Linux : pipe()
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h> //waitpid() 함수를 위해 사용
int main(int argc, char **argv){
pid_t pid;
int pfd[2];
char line[BUFSIZ]; // <stdio.h> 파일에 정의된 버퍼 크기로 결정
int status;
if(pipe(pfd)<0){
perror("pipe()");
return -1;
}
if((pid=fork())<0){
perror("fork()");
return -1;
}else if(pid==0){ // 자식 프로세스인 경우의 처리
close(pfd[0]); // 읽기를 위한 파일 디스크립터 닫기
dup2(pfd[1],1); // 쓰기를 위한 파일 디스크립터를 표준 출력(1)로 변경
execl("/bin/date","date",(char *)0); // date 명령어 수행
/*
'\0' is not a null pointer, it's a null character. So the value (0) is correct, it's just the type is wrong.
*/
close(pfd[1]); // 쓰기를 위한 파일 디스크립터 닫기
_exit(127);
}else{ // 부모 프로세스인 경우의 처리
close(pfd[1]); // 쓰기를 위한 파일 디스크립터 닫기
if(read(pfd[0],line,BUFSIZ)<0){ // 파일 디스크립터로부터 데이터 읽기
perror("read()");
return -1;
}
printf("%s\n",line);
close(pfd[0]); // 읽기를 위한 파일 디스크립터 닫기
waitpid(pid,&status,0); // 자식 프로세스의 종료 기다리기
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment