c - execvp() 系统调用未执行

标签 c

char *args[41];
char str[41], teststr[41];
const char delimiter[2]=" ";
memcpy(teststr, str, sizeof(str));
args[i]=strtok(teststr, delimiter);
while(args[i]!=NULL)
{
    printf("args[%d]=%s\n", i, args[i]);
    i++;
    args[i]=strtok(NULL, delimiter);
}

这是我用来初始化 args[] 的代码。

下面的代码是执行execvp()系统调用。

pid=fork();
if(pid==0)
{
    execvp(args[0], args);
}

当我运行代码时,execvp 运行了几个命令。例如,当我尝试执行“ls”命令时,它会起作用,但当我尝试运行“date”命令或“cd”命令时,它不起作用。当我尝试执行“cat”命令时,提示没有显示任何内容,同时它也没有出现。

最佳答案

看起来您对如何获取参数有疑问,但由于您没有显示您的输入,因此很难判断。 strtok() 修改您传递给它的字符串,因此存储指向您正在修改的字符串的指针看起来很麻烦。

这会做你想做的:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAX_BUFFER_LEN 1024
#define MAX_ARGS 100

int main(void) {
    char command[MAX_BUFFER_LEN];

    printf("myshell> ");
    fflush(stdout);
    fgets(command, MAX_BUFFER_LEN, stdin); 
    command[strlen(command) - 1] = '\0';

    char * args[MAX_ARGS];
    char * temparg;
    int i = 0;

    temparg = strtok(command, " ");
    while ( temparg ) {
        args[i] = strdup(temparg);
        ++i;
        temparg = strtok(NULL, " ");
    }

    i = 0;
    while ( args[i] != NULL ) {
        printf("Argument %d: %s\n", i + 1, args[i]);
        ++i;
    }

    pid_t my_pid = fork();
    if ( my_pid == 0 ) {
        execvp(args[0], args);
    }

    wait(NULL);

    return EXIT_SUCCESS;
}

哪些输出:

paul@MacBook:~/Documents/src/scratch$ ./exectest
myshell> cat exectest.c
Argument 1: cat
Argument 2: exectest.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAX_BUFFER_LEN 1024
#define MAX_ARGS 100

int main(void) {
    char command[MAX_BUFFER_LEN];

    printf("myshell> ");
    fflush(stdout);
    fgets(command, MAX_BUFFER_LEN, stdin); 
    command[strlen(command) - 1] = '\0';

    char * args[MAX_ARGS];
    char * temparg;
    int i = 0;

    temparg = strtok(command, " ");
    while ( temparg ) {
        args[i] = strdup(temparg);
        ++i;
        temparg = strtok(NULL, " ");
    }

    i = 0;
    while ( args[i] != NULL ) {
        printf("Argument %d: %s\n", i + 1, args[i]);
        ++i;
    }

    pid_t my_pid = fork();
    if ( my_pid == 0 ) {
        execvp(args[0], args);
    }

    wait(NULL);

    return EXIT_SUCCESS;
}

paul@MacBook:~/Documents/src/scratch$ 

为简洁起见省略了一些错误检查。

关于c - execvp() 系统调用未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21871325/

相关文章:

C 将二维数组传递给函数

C 格式 printf(%Lf) 结果错误

c - C 中的 free 和 C++ 中的 delete 之间的区别?

c - 使用直接寄存器寻址时出现 PC-Lint 错误

c - read 将 stdout 从无缓冲更改为在规范模式下缓冲的行

c - 解决访问冲突

C - 并行执行 fork() 时 wait(NULL) 的含义

c - 如何在 C 中减少 FILE* 指针

c - 为什么复制内存时出现段错误

c - "const int *ptr=&i"到底是什么意思?为什么它接受非常量地址?