execvp()启动的进程退出一些命令

时间:2013-11-29 14:02:08

标签: c execvp

我使用此代码运行一些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;
}

2 个答案:

答案 0 :(得分:1)

请记住,execvp 不会返回

答案 1 :(得分:1)

正如Kerrek SB所说,execvp没有回来。

添加更多信息:execv - 函数系列将您的进程(正在运行的程序)替换为另一个。与fork合作,这是在system()电话中发生的事情。

更坦率地说:

如果要从C程序运行系统命令,并根据“返回”值继续执行,则应使用system()调用。请参阅example

如果要生成应运行另一个可执行文件的子进程,则应fork,并在子进程内使用execv。请参阅以下example