在输入,输出和重定向中使用execvp [英] Using execvp with Input,Output and redirection

查看:328
本文介绍了在输入,输出和重定向中使用execvp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C程序中,假设我要使用Exec函数来执行给定程序,例如,如果我只想尝试ls -l我将做类似的事情

In a C program, let's say i wann use Exec functions for executing a given program, for example if i wanna just try ls -l i'll do something like

args[0]="ls";
args[1]="-l";
args[2]=NULL;

...
execvp("ls", args); 

一切都很好.现在,如果我还想将重定向添加到文件(或stderr),该怎么办? 我被困住了,很明显,将> log.txt作为数组的第3个条目添加是行不通的,但是我不知道如何进行.

and it's all fine. Now what if i wanna also add the redirection to a file (or to stderr)? I'm stuck, it's obvious that adding >log.txt as a 3rd entry in the array won't work, but I don't know how to proceed.

而且,如果我想传递一些输入参数怎么办?如果我想执行GCC命令,例如"gcc -o in redirection> log.txt",该怎么办?

And also, what if I wanna pass some Input parameters? What if i wanna execute a GCC command like "gcc -o out in redirection>log.txt" ?

[评论更新:]

这是一个C程序,它模拟可以运行字符串",包含命令,参数列表,输入和重定向的字符串的shell.

It's a C program that simulate a shell which can "run strings", string that contains a command, a list o parameters, input and a redirection.

推荐答案

只需设置文件描述符,因为exec -d进程将找到它们,然后执行.
为此,您需要opendup2close.

Just set up your file descriptors as the exec-d process shall find them and then do the exec.
For that you need open, dup2 and close.

exec系列中的所有功能只是用您说的任何内容替换当前进程.

All functions in the exec-family just replace the current process with whatever one you say.

这篇关于在输入,输出和重定向中使用execvp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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