【问题标题】:Trying to pass user input into a simple shell that I am creating试图将用户输入传递到我正在创建的简单外壳中
【发布时间】:2016-03-01 03:23:40
【问题描述】:

我正在创建一个简单的外壳。用户输入一个系统调用,对于用户输入的任何命令,我在子进程上分叉并调用 execvp。我进行了调试,似乎我传递给 execvp 的参数不正确。有人可以帮帮我吗,我是C的新手

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80
int main(void){
    char *args[MAXLINE/2 + 1]; 
    char buf[MAXLINE/2 + 1];

    int should_run = 1; 
    printf("Shell\n");
    fgets(buf, MAXLINE,stdin);
    buf[strlen(buf)-1] = '\0';
    int i=0;
    char *token;
    token = strtok(buf," ");
    while(token != NULL){
        args[i++] = token;
        token = strtok(NULL," ");
    }

    while(should_run){
        if(strcmp(args[0],"exit") == 0){
            should_run = 0;
            break;
        }
        pid_t pid;
        pid = fork();

        //child process
        if(pid == 0){
            execvp(args[0],args);
        }
        else{

            wait(0);
            //Also how do I make it so that the program starts from top again, meaning it lets the user enter another system call
        }
    }
}

【问题讨论】:

  • execvp man page says this 关于第二个参数:“指针数组必须由 NULL 指针终止”。

标签: c shell


【解决方案1】:

execvp 函数要求您以 NULL 终止列表本身。目前,您的标记化循环不会在最后一个标记上放置 NULL,因此行为未定义(您从未初始化过数组)。

一个紧凑(但不是很漂亮)的解决方案是像这样重新排列你的循环:

int i = 0;
char *token;
do {
    token = strtok( i == 0 ? buf : NULL," ");
    args[i++] = token;
} while( token != NULL );

【讨论】:

  • 什么是更漂亮的解决方案?
  • 在我看来“更漂亮”是不要在循环内使用分支。但这是主观的。这应该可以很好地完成工作。
猜你喜欢
  • 2021-07-16
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2021-02-03
  • 1970-01-01
  • 2013-12-16
  • 2022-10-04
  • 1970-01-01
相关资源
最近更新 更多