本文介绍了重定向到execvp()的内部调用不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在执行一个小程序,该程序使用execvp()执行给定命令.当不使用重定向时,但当我运行以下命令时,它可以正常工作:

I've been implementing a small program that executes a given command using execvp(). It works fine when not using redirection, but when I run a command such as:

cat file1.txt > redirected.txt

cat输出以下错误消息并失败:

cat outputs the following error messages and fails:

cat: >: No such file or directory
cat: redirected.txt: No such file or directory

我已经进行了一些深入的研究,我开始认为也许execvp()不允许进行重定向,因为它不在shell中运行.这是否意味着我将不得不在发生重定向时手动选择并在fork/exec代码中使用管道来解决此限制?有没有比使用execvp()更好的方法了?

I've done some digging around and I'm starting to think that perhaps execvp() isn't allowed to do redirection because it doesn't run in the shell. Does that mean that I would have to manually pick out when redirection occurs and use pipes in my fork/exec code to get around this restriction? Is there a better way than to use execvp()?

谢谢!

推荐答案

您的执行给定命令的小程序"实质上是一个外壳.由于您正在编写外壳程序,因此您可以根据需要使用任何语法来实现重定向. >重定向运算符不是内核的功能,它是Shell的功能.

Your "small program that executes a given command" is essentially a shell. Since you are writing a shell, it is your job to implement redirections with whatever syntax you desire. The > redirection operator is not a feature of the kernel, it is a shell feature.

要实现sh样式的重定向,必须分析命令,找到重定向操作符,打开文件并将它们分配给输入/输出描述符.必须在调用execvp之前 完成.查找dup2系统调用.

To implement sh-style redirection, you must parse the command, locate the redirection operators, open the files and assign them to input/output descriptors. This must be done before calling execvp. Look up the dup2 system call.

这篇关于重定向到execvp()的内部调用不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 18:20