Implementing Pipes in a C shell (Unix)
You should be able to implement pipes and output redirection with your shell, but there are a few things I noticed:
- Your code for reading input, parsing, and output are mixed together, you may want to separate this functionality.
- strtok won't work very well as a parser for shell commands. It will work for very simple commands, but you may want to look into creating or finding a better parser. A command like
echo "hello world"
will be problematic with your current parsing method. - You may want to create a simple structure for holding your parsed commands.
Here is some pseudocode to get you started:
#define MAX_LINE 10000#define MAX_COMMANDS 100#define MAX_ARGS 100// Struct to contain parsed inputstruct command{ // Change these with IO redirection FILE *input; // Should default to STDIN FILE *output; // Should default to STDOUT int num_commands; int num_args[MAX_COMMANDS]; // Number of args for each command char* command_list[MAX_COMMANDS]; // Contains the programs to be run char* args_list[MAX_COMMANDS][MAX_ARGS]; // The args for each command boolean background_task; boolean append;}int main(){ char input[MAX_LINE]; while (1) { struct command cmd; print_prompt(); read_input(input); parse_input(input, &cmd); execute(&cmd); }}
Good luck with this project!
Pipes and redirections are different, actually. To implement a redirection (such as >>
) you have to use dup2
indeed. First, open the desired file with appropriate flags (for >>
they'll be O_WRONLY|O_CREAT|O_APPEND
). Second, using dup2
, make stdout (file descriptor 1) a copy of this newly opened fd. Finally, close newly opened fd.
To create a pipe, you'll need a pipe
syscall. Read its manpage, it contains example code. Then you'll also need dup2
to make file descriptors returned by pipe
be stdin for one process and stdout for another, respectively.