//
// Created by beokwithanything on 2020/11/13.
//
#include "stdio.h"
#include "fcntl.h"
#include "unistd.h"
#include "stdlib.h"
#include "string.h"
void sys_error(const char *str) {
perror(str);
exit(1);
}
int main () {
int pid = fork();
if (pid == -1) {
sys_error("fork error");
} else if (pid == 0) {
int fd1 = open("../mmap/file.txt", O_WRONLY);
if (fd1 < 0) {
sys_error("open error");
}
char *str = "this is a text for parent";
write(fd1, str, strlen(str));
printf("child write success\n");
} else {
int fd2 = open("../mmap/file.txt", O_RDONLY);
if (fd2 < 0) {
sys_error("open error");
}
sleep(1); // sure child write finished
char buf[1024];
int len = read(fd2, buf, sizeof(buf));
write(STDOUT_FILENO, buf, len);
}
return 0;
}
读管道、套接字 会阻塞,文件不会阻塞。也就是说,如果父进程先读,子进程再写,父进程得到的就是 “”