C 在 execvp 中传递一个参数和两个参数

标签 c string char execvp

我正在为我的学校项目和 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/

相关文章:

c# - 将字符串转换为 byte[] 会创建零字符

c - 尝试访问 C 中字符串数组的第一个字符时出现段错误

c - 在运行令人尴尬的并行作业时,避免并行文件系统过载的最佳方法是什么?

.net - Delphi至.Net格式的字符串转换

c# - 在@字符串中添加双引号

c - 从字符集高效地创建顺序词表

c++ - 如何使用Qt QSerialPort发送十六进制0x00

C 动态数据说明符

c - recv() 收到不正确的数据

在虚拟 ramdisk 中创建 mmap