开发者

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

I am t开发者_如何转开发rying to write a simple shell program and am having problems with file redirection for non built-in commands. For example ./a.out < infile > outfile, would have the user complied program a.out take input from infile and output its output to outfile instead of the streams that it normally uses. When I encounter a non built-in command I fork a new process and overlay a new image with the provided arguments. The general format is command arg1 arg2 ... argn < infile > outfile. So the args (arg1 to argn) would be passed in the new image and the input and outputs would be changed to infile and outfile Here is a snippet of what my forking 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 was also thinking that there might be a way to change stdin and stdout in the new image? Any links or info would be appreciated.


On Unix, you generally want dup2 for this. See libc docs for duplicating file descriptors.


In the forked process, just before exec-ing the new image, close file handles 0 (stdin), 1 (stdout) and possibly 2 (stderr).

Then use open() to open the necessary files in the correct order (stdin, out, and err). They will each use the first entries in the file handles table - 0, 1 and 2. So the first file you open will be treated as stdin from now on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜