Created
April 3, 2024 14:47
-
-
Save rajkumar-p/caeca97bbba5c81bc00caf9c684c7936 to your computer and use it in GitHub Desktop.
A sample shell like program that runs: ls -lt | wc -l
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 <cstring> | |
| #include <iostream> | |
| #include <sys/wait.h> | |
| #include <unistd.h> | |
| int main(int argc, char *argv[], char *envp[]) { | |
| int p_fds[2]; | |
| if (pipe(p_fds) == -1) { | |
| std::cerr << "Error: pipe() - " << strerror(errno) << std::endl; | |
| exit(1); | |
| } | |
| std::cout << "Parent with PID: " << getpid() << " executing..." << std::endl; | |
| switch (int pid = fork()) { | |
| case -1: | |
| std::cerr << "Error: fork() failed - " << strerror(errno) << std::endl; | |
| exit(1); | |
| break; | |
| case 0: | |
| // Child | |
| std::cout << "Child (ls -lt) with PID: " << getpid() << " executing..." | |
| << std::endl; | |
| dup2(p_fds[1], 1); | |
| close(p_fds[0]); | |
| execl("/usr/bin/ls", "ls", "-lt", NULL); | |
| break; | |
| default: | |
| // Parent | |
| break; | |
| } | |
| // To fork wc, that will read cat output | |
| switch (int pid = fork()) { | |
| case -1: | |
| std::cerr << "Error: fork() failed - " << strerror(errno) << std::endl; | |
| exit(1); | |
| break; | |
| case 0: | |
| // Child | |
| std::cout << "Child (wc -l) with pid " << getpid() << " executing..." | |
| << std::endl; | |
| dup2(p_fds[0], 0); | |
| close(p_fds[1]); | |
| execl("/usr/bin/wc", "wc", "-l", NULL); | |
| break; | |
| default: | |
| // Parent | |
| break; | |
| } | |
| close(p_fds[0]); | |
| close(p_fds[1]); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment