如何为n个子进程实现n个管道?代码发送char*失败求助
Hey there, fellow sys programming newbie! I totally get how frustrating it is when your pipe/process setup doesn't work as expected—let's work through this together.
First off, to help troubleshoot exactly what's going wrong, could you share two key details:
- The exact error messages you're seeing (copy-paste them if you can!)
- Your full code, especially the parts handling pipe creation,
fork(), and theread()/write()calls
In the meantime, here are some super common pitfalls that trip up new sys programmers when working with pipes and child processes:
Common Issues to Check
- Unclosed Pipe File Descriptors: When you create a pipe with
pipe(fd), you get two file descriptors:fd[0](read end) andfd[1](write end). After forking, you must close the unused ends in both parent and child. For example, if the parent is writing to a child, the parent should closefd[0], and the child should closefd[1]. Leaving unused fds open can makeread()hang forever because the kernel thinks there's still an active writer/reader connected. - Botched Fork Handling: Always check all three return cases of
fork():-1: Fork failed (handle this withperror()!)0: You're in the child process- Positive integer: You're in the parent, this is the child's PID
Skipping error checks here can lead to weird, hard-to-debug behavior.
- Partial Reads/Writes:
read()andwrite()don't always process all your data in one call. For strings, make sure you either write the null terminator explicitly or track the length when reading. If you're expecting a full message, you might need to loopread()until you get all the bytes you're waiting for. - Mismatched Pipes and Children: If you're creating n pipes for n children, double-check that each child is using the correct pipe. It's easy to mix up indices in an array of pipes, leading to messages going to the wrong child (or nowhere at all).
Example Working Code
Here's a simple, tested example that creates n children and pipes, then sends a unique message to each child:
#include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/wait.h> #include <stdlib.h> int main(int argc, char *argv[]) { if (argc != 2) { fprintf(stderr, "Usage: %s <number-of-children>\n", argv[0]); return 1; } int n = atoi(argv[1]); int pipes[n][2]; pid_t child_pids[n]; // Step 1: Create all pipes first before forking for (int i = 0; i < n; i++) { if (pipe(pipes[i]) == -1) { perror("Failed to create pipe"); return 1; } } // Step 2: Fork each child process for (int i = 0; i < n; i++) { child_pids[i] = fork(); if (child_pids[i] == -1) { perror("Failed to fork child"); return 1; } else if (child_pids[i] == 0) { // Child process: Clean up unused pipes for (int j = 0; j < n; j++) { close(pipes[j][1]); // Close all write ends (child only reads) if (j != i) { close(pipes[j][0]); // Close read ends of other pipes } } // Read message from our assigned pipe char buffer[256]; ssize_t bytes_read = read(pipes[i][0], buffer, sizeof(buffer) - 1); if (bytes_read == -1) { perror("Child failed to read"); _exit(1); } buffer[bytes_read] = '\0'; // Null-terminate the received string printf("Child %d: Received message -> %s\n", i, buffer); // Clean up our pipe's read end close(pipes[i][0]); _exit(0); } } // Step 3: Parent process - send messages to each child for (int i = 0; i < n; i++) { close(pipes[i][0]); // Close read end (parent only writes) char message[256]; snprintf(message, sizeof(message), "Hi from parent to child #%d!", i); ssize_t bytes_written = write(pipes[i][1], message, strlen(message)); if (bytes_written == -1) { perror("Parent failed to write"); return 1; } close(pipes[i][1]); // Close write end after sending } // Step 4: Wait for all children to finish for (int i = 0; i < n; i++) { waitpid(child_pids[i], NULL, 0); } return 0; }
Key Takeaways From the Example
- We create all pipes before forking, so every child inherits all pipe fds.
- Both parent and child close unused pipe ends immediately to avoid hanging.
- We use
waitpid()to make sure the parent doesn't exit before children finish processing messages. - We null-terminate the received string so it's printable correctly.
Once you share your error messages and code, we can pinpoint exactly where your setup is going wrong!
内容的提问来源于stack exchange,提问作者yassine yousfi
相关产品推荐
相关产品推荐

