Simple redirection of unix shell file for non-builtin commands

I am trying to write a simple shell program and am having trouble redirecting files for non-built-in commands. For instance. /a.out <infile> outfile, would execute a.out user program to get input from infile and output its output to outfile instead of the streams that it normally uses. When I come across a non-built-in command, I create a new process and overlay a new image with the arguments provided. The general format is the command arg1 arg2 ... argn <infile> outfile. Thus, args (arg1 to argn) will be transferred in the new image, and the input and output will be changed to infile and outfile. Below is a snippet of what my blending process looks like.

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 will allow me to do this? I also thought that there might be a way to change stdin and stdout in a new image? Any links or information would be appreciated.

+3
source share
2 answers

On Unix, you usually want dup2to do this. See libc docs for duplicate file descriptors.

+2
source

In a bifurcated process, before exec-in a new image, close the file descriptors 0 (stdin), 1 (stdout), and possibly 2 (stderr).

open(), (stdin, out err). - 0, 1 2. , , , stdin.

+2

Source: https://habr.com/ru/post/1789661/


All Articles