Created
November 24, 2023 22:07
-
-
Save EteimZ/7b9127efb054a45afce5af0c7f40e356 to your computer and use it in GitHub Desktop.
A simple example demonstratin piping in C
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #include <stdio.h> | |
| #include <stdlib.h> | |
| #include <unistd.h> | |
| #include <string.h> | |
| #include <sys/wait.h> | |
| int main() { | |
| int pipefd[2]; // File descriptors for the pipe | |
| // Create the pipe | |
| if (pipe(pipefd) == -1) { | |
| perror("Pipe creation failed"); | |
| exit(EXIT_FAILURE); | |
| } | |
| // Fork a child process | |
| pid_t pid = fork(); | |
| if (pid == -1) { | |
| perror("Fork failed"); | |
| exit(EXIT_FAILURE); | |
| } | |
| if (pid == 0) { | |
| // Child process (writer) | |
| // Close the read end of the pipe | |
| close(pipefd[0]); | |
| // Data to be sent | |
| const char *message = "Hello, Parent!"; | |
| // Write data to the pipe | |
| write(pipefd[1], message, strlen(message)); | |
| // Close the write end of the pipe | |
| close(pipefd[1]); | |
| exit(EXIT_SUCCESS); | |
| } else { | |
| // Parent process (reader) | |
| // Close the write end of the pipe | |
| close(pipefd[1]); | |
| // Buffer to store the received data | |
| char buffer[100]; | |
| // Read data from the pipe | |
| ssize_t bytesRead = read(pipefd[0], buffer, sizeof(buffer)); | |
| if (bytesRead == -1) { | |
| perror("Read failed"); | |
| exit(EXIT_FAILURE); | |
| } | |
| // Close the read end of the pipe | |
| close(pipefd[0]); | |
| // Null-terminate the received data | |
| buffer[bytesRead] = '\0'; | |
| printf("Received message from child: %s\n", buffer); | |
| // Wait for the child process to finish | |
| wait(NULL); | |
| exit(EXIT_SUCCESS); | |
| } | |
| return 0; | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment