Home > Article > Backend Development > How to Execute a Child Process with Piped Stdin/Stdout in Linux?
Executing a Child Process with Piped Stdin/Stdout in Linux
In Linux, executing a child process with pipedstdin/stdout requires a combination of Linux syscalls or POSIX functions. To achieve this, we'll utilize the following techniques:
Below is a C example that implements these techniques:
#include <iostream> #include <unistd.h> #include <stdlib.h> using namespace std; int main() { // Input string string s = "Hello, world!"; // Create pipes for stdin and stdout int stdinPipe[2], stdoutPipe[2]; pipe(stdinPipe); pipe(stdoutPipe); // Fork a child process int pid = fork(); if (pid == 0) { // Child process // Redirect stdin and stdout to pipes dup2(stdinPipe[0], STDIN_FILENO); // Read from pipe dup2(stdoutPipe[1], STDOUT_FILENO); // Write to pipe // Close unused file descriptors close(stdinPipe[1]); close(stdoutPipe[0]); // Execute "foo" with piped stdin execlp("foo", "foo", NULL); // Exit child process on failure exit(1); } else if (pid > 0) { // Parent process // Close unused file descriptors close(stdinPipe[0]); close(stdoutPipe[1]); // Write to stdin pipe write(stdinPipe[1], s.c_str(), s.length()); close(stdinPipe[1]); // Read from stdout pipe char buffer[256]; int bytesRead = 0; string output; while ((bytesRead = read(stdoutPipe[0], buffer, sizeof(buffer))) > 0) { output.append(buffer, bytesRead); } close(stdoutPipe[0]); // Print output string cout << output << endl; } return 0; }
This code snippet:
The above is the detailed content of How to Execute a Child Process with Piped Stdin/Stdout in Linux?. For more information, please follow other related articles on the PHP Chinese website!