C – Simple shell program unix file redirection for non-built-in commands

Simple shell program unix file redirection for non-built-in commands… here is a solution to the problem.

Simple shell program unix file redirection for non-built-in commands

I’m trying to write a simple shell program, but I’m having trouble with file redirection for non-built-in commands. For example, ./a.out < infile > outfile causes the user to compile the program a.out to get input from infile and output it to outfile instead of the stream it normally uses. When I come across a command that is not built-in, I fork a new process and overwrite a new image with the provided parameters. The general format is command arg1 arg2 … argn < infile > outfile。 So args (arg1 to argn) will be passed in the new image, the input and output will be changed to infile and outfile This is a fragment of my fork process.

pid = fork();

if (pid < 0) {
   fprintf(stderr, "*** fork error ***\n");
} else if (pid == 0) {
   execvp(command, args);
}

waitpid(pid, &status, 0);

Is there a unix command that allows me to do this? I was also thinking that there might be a way to change the standard input and standard output in the new image? Any links or information would be appreciated.

Solution

On Unix, you usually need dup2 for this. See also libc docs for copying file descriptors.

Related Problems and Solutions