00:46:00
DAGE-856 - 写入文件 return 0;}```There is a shared file pointer in the main process, and after reclin, the two child processes each have their own file pointers that point to the same file. The two child processes write to the file at the same time, the order is chaotic. Because the order of writing is random for each child process.```c#include <stdio.h>#include <fcntl>#include <unistd>#include <wait.h>#include <string.h>int main() { int fd = open("test.txt", O_RDWR | O_CREAT, 0777); if (fork() == 0) { //Child process write char *buf = "I am child"; write(fd, buf, strlen(buf)); printf("Child process fork"); } else { int fd = open("test.txt", O_RDWR | O_CREAT, 0777); //Father process write char *buf = "I am father"; write(fd, buf, strlen(buf)); printf("Father process fork"); } return 0;}```Now, if you open the file in each process, the order will be correct. Each child process has its own separate file pointer, so they will not interfere with each other.```c#include <stdio at>#include <fcstl>#include <unistd>#include <wait.h>#include <string.h>int main() { int fd = open("test.txt", O_RDWR | O_CREAT, 0777); if (fork() == 0) { //Child process write int fd = open("test.txt", O_RDWR | O_CRE, 0777); char *buf = "I am child"; write(fd, buf, strlen(buf)); printf("Child process fork"); } else { int fd = open("test.txt", O_RDWR | O_CREAT, 0777); //Father process write char *buf = "I am father" write(fd, buf, strlen(buf)); printf("Father process fork"); } return 0;}```
2015年12月23日