c
[C] write하고 read하면 결과가 제대로 안 나온다?
ohojee
2023. 2. 28. 16:06
int main(){
int fd;
char *buf;
char str[5] = "hello";
fd = open("abc.txt", O_RDWR);
printf("fd: %d \n", fd);
int j = write(fd, str, 5);
printf("write return : %d\n", j);
int i = read(fd, buf, 5);
printf("read return: %d %s\n",i,buf);
exit(0);
}
왜 write하고 read하면 write는 fd에 잘 들어가는데 read는 하지 못하는가,,,
❗️❗️❗️❗️❗️❗️❗️
write한 후 fd를 닫지 않으면 fd는 open된 상태이기 때문에 EOF 조건에 충족하지 않았다고 판단(어? 파일 열려있는데 아직 쓰고 있을지도 몰라!)하고 계속 읽게 된다
그러면 read를 멈추지 않고 계속 읽게 된다
=> write 후 다 썼다면 fd를 닫아주어야 함!
int main(){
int fd;
char *buf;
char str[5] = "hello";
fd = open("abc.txt", O_RDWR);
printf("fd: %d \n", fd);
int j = write(fd, str, 5);
printf("write return : %d\n", j);
close(fd);
fd = open("abc.txt", O_RDWR);
int i = read(fd, buf, 5);
printf("read return: %d %s\n",i,buf);
exit(0);
}
이렇게 닫고 다시 열어주면
올바르게 출력이 된다!
참고 블로그
https://velog.io/@suseodd/Pipe%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80