用c语言编写测试程序,测试fork之前打开文件,父子进程之间是否共享文件 提示: 子进程write 父进程read
时间: 2024-02-20 07:01:11 浏览: 23
可以使用以下 C 语言代码来测试:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <fcntl.h>
int main() {
char *filename = "test.txt"; // 文件名
char *content1 = "Hello, world!"; // 文件内容
char *content2 = " (child process)";
// 父进程打开文件并写入内容
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
write(fd, content1, strlen(content1));
close(fd);
pid_t pid = fork(); // 创建子进程
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
// 子进程打开文件并写入内容
int fd = open(filename, O_WRONLY | O_APPEND);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
write(fd, content2, strlen(content2));
close(fd);
exit(EXIT_SUCCESS);
} else { // 父进程
int status;
wait(&status); // 等待子进程结束
// 父进程读取文件内容
char buf[1024];
int n = 0;
fd = open(filename, O_RDONLY);
if (fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
while ((n = read(fd, buf, sizeof(buf))) > 0) {
write(STDOUT_FILENO, buf, n);
}
close(fd);
exit(EXIT_SUCCESS);
}
}
```
运行上述代码,输出的结果应该为:
```
Hello, world! (child process)
```
这表明父子进程之间共享文件,子进程可以在父进程打开的文件中写入内容,并且父进程可以读取到子进程写入的内容。