1

我使用此代码运行一些 shell 命令,但它在ls命令后退出。:我错在哪里?

#include <stdio.h>
#include <unistd.h>
#include <errno.h>

#define MAX_LINE 80 /* The maximum length command */

void setup(char inputBuffer[], char *args[],int *background)
{
    int length,  i, start, ct;    

    ct = 0;

    /* read what the user enters on the command line */
    length = read(STDIN_FILENO,inputBuffer,MAX_LINE);  
    start = -1;
    if (length == 0)
        exit(0);            /* ^d was entered, end of user command stream */

    if ( (length < 0) && (errno != EINTR) ) {
        perror("error reading the command");
    exit(-1);           /* terminate with error code of -1 */
    }

    printf(">>%s<<",inputBuffer);
    for (i=0;i<length;i++){ /* examine every character in the inputBuffer */

        switch (inputBuffer[i]){
        case ' ':
        case '\t' :               /* argument separators */
    if(start != -1){
                args[ct] = &inputBuffer[start];    /* set up pointer */
        ct++;
    }
            inputBuffer[i] = '\0'; /* add a null char; make a C string */
    start = -1;
    break;

            case '\n':                 /* should be the final char examined */
    if (start != -1){
                args[ct] = &inputBuffer[start];     
        ct++;
    }
            inputBuffer[i] = '\0';
            args[ct] = NULL; /* no more arguments to this command */
    break;

        default :             /* some other character */
    if (start == -1)
        start = i;
            if (inputBuffer[i] == '&'){
      *background  = 1;
              inputBuffer[i-1] = '\0';
    }
} /* end of switch */
 }    /* end of for */
 args[ct] = NULL; /* just in case the input line was > 80 */

for (i = 0; i <= ct; i++)
         printf("args %d = %s\n",i,args[i]);
} /* end of setup routine */

int main(void)
{
char inputBuffer[MAX_LINE]; /*buffer to hold command entered */
    int background; /* equals 1 if a command is followed by '&' */
    char *args[MAX_LINE/2 + 1]; /*command line arguments */
int should_run = 1; /* flag to determine when to exit program */
while (should_run) {
    //background=0;
    printf("Msh>");
    fflush(stdout);
    setup(inputBuffer, args, &background);
    execvp(args[0], args);
}
return 0;
}
4

2 回答 2

1

记住execvp 不返回

于 2013-11-29T14:02:53.290 回答
1

正如Kerrek SB 已经说过的,execvp不会返回。

添加更多信息:execv-family 函数将您的进程(正在运行的程序)替换为另一个。这与调用fork内部发生的事情相配合system()

说得更直白一点:

如果你想从你的 C 程序运行一个系统命令,并基于“返回”值进行,你应该使用system()调用。见例子

如果你想生成一个应该运行另一个可执行文件的子进程,你应该fork在子进程内部使用execv. 请参见以下示例

于 2013-11-29T14:11:56.677 回答