Я новичок в мире POSIX и пытаюсь понять, как системный вызов fork работает в C, особенно как он копирует файловые дескрипторы и буферы от родительского элемента к дочернему. В частности, эти два случая:
Случай 1:
У меня есть простая программа, которая что-то печатает
printf "start"
fork
parent:
print something
child
print something
В результате один раз печатается слово «start», а затем родительский и дочерний блоки. Это означает, что fork очищал буферы ввода-вывода перед их копированием.
Случай 2:
Та же программа, но теперь я пишу в файл вместо стандартного вывода.
В результате файл начинает печатать дважды, что для меня странно. Очищает ли fork только стандартные буферы, а не файловые буферы?
Программа, использованная для тестирования:
#include
#include
#include
#include
#include
#include
int main() {
pid_t pid;
FILE *fd;
// Open a file in writing mode
fd = fopen("filename.txt", "w");
// Write some text to the file
fprintf(fd, "Started\n");
// Create a child process
pid = fork();
if (pid < 0) {
// Fork failed
fprintf(stderr, "Fork failed\n");
fclose(fd);
return 1;
} else if (pid == 0) {
// This is the child process
const char *child_message = "Hello from the child process!\n";
fprintf(fd, child_message);
fclose(fd); // Close the file descriptor in the child process
exit(0);
} else {
// This is the parent process
const char *parent_message = "Hello from the parent process!\n";
fprintf(fd, parent_message);
// Wait for the child process to complete
wait(NULL);
// Write a final message from the parent
const char *completion_message = "Child process completed.\n";
fprintf(fd, completion_message);
fclose(fd); // Close the file descriptor in the parent process
}
return 0;
}
Подробнее здесь: https://stackoverflow.com/questions/785 ... rk-syscall