比execlp(cmd [0],cmd [0],cmd [1],cmd [2],cmd [3] NULL)更有效的方法; [英] A more efficient way than: execlp(cmd[0], cmd[0], cmd[1] cmd[2], cmd[3] NULL);
问题描述
我正在尝试制作一个命令行Iinterface程序,该程序可以从用户输入中获取代码行并使用execlp执行它们.
i am trying to make a Command Line Iinterface program that can get line of code from user input and execute them using execlp.
我想知道是否有更好的方式编写代码.
I wanna know if there is a better way of writing my code.
execlp(cmd[0], cmd[0], cmd[1] cmd[2], cmd[3] NULL);
perror("Execlp");
例如,用户输入4个单词,每个单词将存储在:
For example user enter 4 words and each of them will be store in:
cmd[0] cmd[1] cmd[2] cmd[3]
如果我们使用cc helloworld.c -o helloworld
的编译功能
这将在数组cmd[]
if we use compile function which is cc helloworld.c -o helloworld
this will require 4 space inside array cmd[]
或者我们使用./helloworld
它将存储在cmd[0]
中并运行它,这很好用
it will be store in cmd[0]
and run it, great this works
但是我假设如果有一个功能需要四个以上的单词,我的程序将能够执行它们吗?答案可能是否",例如:如果有5个或更多的单词,我不认为我的程序能够运行它,除非在我的函数中它将有5个元素起作用
but i assume what if there is a function which require more than 4 words, will my program be able to execute them? Answer is probably no, E.g.: if theres is 5 or more words , i dont think my program will be able to run it unless in my function it will have 5 element to work
execlp(cmd[0], cmd[0], cmd[1] cmd[2], cmd[3]. cmd[4], NULL);
或
execlp(cmd[0], cmd[0], cmd[1] cmd[2], cmd[3], cmd[4], cmd[5], cmd[6], NULL);
perror("Execlp");
是否有更有效的方法来做到这一点?通过使用exec()
系列中的其他功能.
Is there a more efficient way to do this? by using other function within exec()
family.
谢谢:)
推荐答案
使用execvp()
怎么办?例如:
[STEP 110] # cat execvp.c
#include <unistd.h>
int
main(int argc, char *argv[])
{
/* argv[argc] is always NULL */
execvp(argv[1], &argv[1]);
return 0;
}
[STEP 111] # gcc -Wall execvp.c
[STEP 112] # ./a.out echo 1
1
[STEP 113] # ./a.out echo 1 2
1 2
[STEP 114] # ./a.out echo 1 2 3
1 2 3
[STEP 115] #
这篇关于比execlp(cmd [0],cmd [0],cmd [1],cmd [2],cmd [3] NULL)更有效的方法;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!