我正在为我的学校项目和 atm 开发一个简单的 shell,我试图传递两个输入参数以与命令一起使用(例如:ls/home/-l),因为我只能传递 1 个 atm。这意味着“/home/”之后的任何内容都不会被执行。我已经尝试过这个方法来解决这个问题,但没有成功,我不知道该怎么办。
编辑:抱歉 此行只是为了可视化这些变量是什么: pid = fork() 、 char* = arg[30] 、 char = input 。
if(pid != 0) {
waitpid(-1, &stat, 0) ;
}
else {
if(arg[2]!=0) {
char* doubleArgument = (char *) malloc(1 + strlen(arg[1])+ strlen(arg[2]) ) + 1;
strcpy(doubleArgument, arg[1]) ;
strcpy(doubleArgument, " ") ;
strcpy(doubleArgument, arg[2]) ;
execvp(input, doubleArgument) ;
}
else {
execvp(input, arg) ;
printf("Error detected at: %s\n", strerror(errno)) ;
exit(-1) ;
}
我该怎么办?如有任何建议 - 谢谢:)
最佳答案
execvp(3): execute file - Linux man page
The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new program. The first argument, by convention, should point to the filename associated with the file being executed. The array of pointers must be terminated by a NULL pointer.
未经测试,试试这个:
char* arg[30] ;
char *input ;
/* set arg and input properly */
pid = fork() ;
if(pid != 0) {
waitpid(-1, &stat, 0) ;
}
else {
if(arg[2]!=0) {
char** doubleArgument = malloc(sizeof(char*) * 4) ;
doubleArgument[0] = input ; /* the file name to execute */
doubleArgument[1] = arg[1] ;
doubleArgument[2] = arg[2] ;
doubleArgument[3] = NULL ;
execvp(input, doubleArgument) ;
}
else {
execvp(input, arg) ;
printf("Error detected at: %s\n", strerror(errno)) ;
exit(-1) ;
}
}
他们说你不应该在 C 中转换 malloc()
的结果。
c - Do I cast the result of malloc? - Stack Overflow
关于C 在 execvp 中传递一个参数和两个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33861605/