[英]Passing argument from command line in my main function and use execvp
I try to pass command line argument "ls -l /user/myuser" in my terminal and execute execvp in my main. 我尝试在终端中传递命令行参数“ ls -l / user / myuser”,并在我的main中执行execvp。
But somehow it gives me this error when i am debugging the code. 但是以某种方式在调试代码时给了我这个错误。
int main(int argc, char *argv[]){
pid_t pid;
pid = fork();
//negative value is failed, 0 is newly created child process
if(pid < 0){
fprintf(stderr, "Fork Failed");
exit(-1);
}else if(pid == 0){
//fork() -> child process
printf("You entered %d commands: \n", argc);
argv[argc + 1] = NULL;
execvp(argv[0],argv);
}else{
wait(NULL);
printf("child complete\n");
exit(0);
}
return 0;
}
argv[0]
is your executable, you need to pass the second argument in this case. argv[0]
是您的可执行文件,在这种情况下,您需要传递第二个参数。 Also don't do argv[argc + 1] = NULL;
也不要做
argv[argc + 1] = NULL;
since the C standard says that argv is NULL terminated. 因为C标准说argv是NULL终止的。 This should work:
这应该工作:
int main(int argc, char *argv[]){
pid_t pid;
pid = fork();
//negative value is failed, 0 is newly created child process
if(pid < 0){
fprintf(stderr, "Fork Failed");
exit(-1);
}else if(pid == 0){
//fork() -> child process
printf("You entered %d commands: \n", argc);
execvp(argv[1],&argv[1]);
}else{
wait(NULL);
printf("child complete\n");
exit(0);
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.