[英]Executing a command with execvp
我有一个要通过调用execvp()
执行的命令字符串数组:
char* commands[] = ["ls -l", "ps -a", "ps"];
char* command = commands[0];
...
如何使用execvp
执行命令?
这是一个可能的用法示例。 这将使命令从其参数开始执行,或者您可以取消注释硬编码示例。
我建议您在各自的手册页中查找所使用的命令。 对于execvp
,声明为
int execvp(const char *file, char *const argv[]);
argv[0]
应该与约定的file
相同,并且argv
应该以NULL
终止。
#include <stdlib.h> //exit
#include <stdio.h> //perror
#include <unistd.h>
#include <sysexits.h>
#include <errno.h>
#include <sys/wait.h>
int main(int argc, char** argv){
int pid, status, ret;
if((pid=fork())<0) { perror("fork"); exit(EX_OSERR); }
if(!pid){ //Child
/*
char* args[] = { "ps", "-a", (char*)0 };
execvp(args[0], args);
*/
//Execute arguments, already NULL terminated
execvp(argv[1], argv+1);
//exec doesn't exit; if it does, it's an error
perror(argv[1]);
//Convert exec failure to exit status, shell-style (optional)
switch(errno){
case EACCES: exit(126);
case ENOENT: exit(127);
default: exit(1);
}
}
//Wait on child
waitpid(pid, &status, 0);
//Return the same exit status as child did or convert a signal termination
//to status, shell-style (optional)
ret = WEXITSTATUS(status);
if (!WIFEXITED(status)) {
ret += 128;
ret = WSTOPSIG(status);
if (!WIFSTOPPED(status)) {
ret = WTERMSIG(status);
}
}
return ret;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.