C语言 如何使用 execvp()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27541910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use execvp()
提问by Axl
The user will read a line and i will retain the first word as a command for execvp.
用户将阅读一行,我将保留第一个单词作为 execvp 的命令。
Lets say he will type "cat file.txt"... command will be cat . But i am not sure how to use this execvp(), i read some tutorials but still didn't get it.
假设他将输入“cat file.txt”...命令将是 cat 。但是我不确定如何使用它execvp(),我阅读了一些教程但仍然没有得到它。
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *buf;
char command[32];
char name[32];
char *pointer;
char line[80];
printf(">");
while((buf = readline(""))!=NULL){
if (strcmp(buf,"exit")==0)
break;
if(buf[0]!=NULL)
add_history(buf);
pointer = strtok(buf, " ");
if(pointer != NULL){
strcpy(command, pointer);
}
pid_t pid;
int status;
if ((pid = fork()) < 0) {
printf("*** ERROR: forking child process failed\n");
exit(1);
}
else if (pid == 0) {
if (execvp(command, buf) < 0) {
printf("*** ERROR: exec failed\n");
exit(1);
}
}
else
while (wait(&status) != pid)
;
free(buf);
printf(">");
}///end While
return 0;
}
回答by Ricky Mutschlechner
The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.
第一个参数是您希望执行的文件,第二个参数是一个以空字符结尾的字符串数组,这些字符串代表手册页中指定的文件的适当参数。
For example:
例如:
char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;
execvp(cmd, argv); //This will run "ls -la" as if it were a command

