父、子各自打开同一个文件实现文件共享的代码
时间: 2023-12-09 21:03:38 浏览: 35
父子进程可以通过共享文件描述符来共享文件。下面是一个示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(void) {
int fd;
pid_t pid;
char buf[256];
// 创建文件并写入数据
fd = open("test.txt", O_CREAT | O_WRONLY, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
write(fd, "hello world\n", 12);
close(fd);
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程打开文件并读取数据
fd = open("test.txt", O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
read(fd, buf, sizeof(buf));
printf("child process read: %s", buf);
close(fd);
_exit(EXIT_SUCCESS);
} else {
// 父进程等待子进程结束
wait(NULL);
// 父进程打开文件并读取数据
fd = open("test.txt", O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
read(fd, buf, sizeof(buf));
printf("parent process read: %s", buf);
close(fd);
}
return 0;
}
```
在这个示例代码中,父进程先创建一个名为 `test.txt` 的文件,写入字符串 "hello world"。然后创建子进程,子进程打开同样的文件,读取文件内容并输出。父进程等待子进程结束后再打开同样的文件,读取文件内容并输出。由于父子进程共享文件描述符,因此它们可以同时访问同一个文件,实现文件共享的效果。