printf重复输出同一语句及进程写入文件问题咨询
Hey there! Let's break down why you're seeing repeated printf output and how to get your program writing PID and parent/child flags to file.txt correctly.
The Root Cause: Fork Duplicates Your Process
When you call fork(), the OS creates an almost identical copy of your parent process—including the current state of your program execution. That means both the parent and child processes will run every line of code that comes after the fork() call.
If your printf and file-writing logic isn't wrapped in a check to distinguish parent vs child, both processes will execute that code twice: once from the parent, once from the child. That's exactly why you're seeing repeated printf statements.
How to Fix It: Use fork()'s Return Value to Branch Logic
The fork() function gives you a clear way to tell which process you're in:
- In the parent process,
fork()returns the PID of the child (a positive integer) - In the child process,
fork()returns0 - If
fork()returns-1, the process creation failed
Here's a corrected example that separates parent/child behavior properly:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> int main() { pid_t fork_result = fork(); // Handle fork failure first if (fork_result == -1) { perror("Failed to create child process"); return EXIT_FAILURE; } // Child process logic (flag = 0) else if (fork_result == 0) { pid_t child_pid = getpid(); printf("Child Process | PID: %d, Flag: 0\n", child_pid); FILE* file = fopen("file.txt", "a"); if (file != NULL) { fprintf(file, "%d, 0\n", child_pid); fclose(file); } else { perror("Failed to open file for child process"); } } // Parent process logic (flag = 1) else { pid_t parent_pid = getpid(); printf("Parent Process | PID: %d, Flag: 1\n", parent_pid); FILE* file = fopen("file.txt", "a"); if (file != NULL) { fprintf(file, "%d, 1\n", parent_pid); fclose(file); } else { perror("Failed to open file for parent process"); } } return EXIT_SUCCESS; }
Extra Tips to Avoid Headaches
- File Writing Safety: When both processes write to the same file, use append mode (
"a") to ensure each write goes to the end. For more critical use cases, add file locking (likeflock()) to prevent race conditions where writes overlap. - Buffer Flushing: Sometimes printf's output buffer gets copied during
fork(), leading to unexpected duplicate lines. To fix this, callfflush(stdout)right beforefork(), or immediately after any printf statements that you don't want duplicated.
内容的提问来源于stack exchange,提问作者Guy

