execvp实际做什么? [英] What does execvp actually do?

查看:108
本文介绍了execvp实际做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
编写外壳程序-如何执行命令

Possible Duplicate:
Writing a shell - how to execute commands

我的任务是用C编写外壳程序.到目前为止,我了解execvp会尝试以arg2作为参数在arg1中运行程序.现在看来,这样做

I've been tasked with writing a shell in C. So far I understand that execvp will try to run the program in arg1 with arg2 as parameters. Now it seems that doing this

execvp ("ls", args); //assume args is {"ls", ">", "awd.txt"}

并不等同于在控制台中输入

is not equivalent to typing this in the console

ls > awd.txt

我意识到我需要使用freopen来获得相同的结果,但是我很好奇execvp在做什么.

I realize that I need to use freopen to achieve the same results but I'm curious what execvp is doing.

推荐答案

exec函数家族最终是系统调用.系统调用直接进入内核,并且通常执行只有内核才能执行的非常特定的服务.

The exec family of functions are ultimately a system call. System calls go straight into the kernel and typically perform a very specific service that only the kernel can do.

另一方面,重定向是一个shell功能.

Redirection, on the other hand, is a shell feature.

因此,当在shell上键入ls > awd.txt时,shell首先执行fork(2),然后在子级中关闭标准输出,然后在文件描述符1上打开awd.txt,从而成为新的标准输出

So, when one types ls > awd.txt at a shell, the shell first does a fork(2), then it closes standard output in the child, then it opens awd.txt on file descriptor one so that it's the new standard output.

然后,只有这样,shell才会进行exec- family系统调用.

Then, and only then, the shell will make an exec-family system call.

在您的情况下,您只需将字符串>awd.txt传递给exec系统调用,然后从那里传递给ls.顺便说一句,请确保使用空指针终止execvp arg数组.

In your case you simply passed the strings > and awd.txt to the exec system call, and from there to ls. BTW, be sure you terminate your execvp arg array with a null pointer.

注意:如您所见,执行程序永远不会看到重定向运算符.在Unix之前,每个程序都必须基于选项将输出定向到文件.更多琐事:大多数程序都不知道它们被重定向了,但是具有讽刺意味的是,ls 确实检查其输出是否为tty,如果是,则执行多列格式化的输出.

Note: As you can see, the redirection operators are never seen by the executed program. Before Unix, directing output to a file had to be done by every program based on an option. More trivia: most programs never know they were redirected, but ironically, ls does check to see if its output is a tty, and if so, it does the multi-column formatted output thing.

这篇关于execvp实际做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆