linux中的子进程shell

时间:2012-02-05 15:57:00

标签: c++ linux

我即将完成我的类项目,该项目包括创建一个执行/ usr / bin /中命令的shell。如果用户输错了命令,shell会使用hamming techinique建议类似的命令。所有这一切都已经完成。

当用户正确输入命令时,shell完美无误地执行。问题是命令不存在时。在这种情况下,我创建候选命令的向量,其汉明权重<= 1(即,它们与用户的输入相差不超过1个字符)。然后我问用户执行哪些命令

例如,如果用户输入sipnote我建议zipnote。如果用户输入'y'来执行命令,它就会完美地执行。问题发生在执行完成之后:它返回到例程的顶部,并且由于某种原因进入例程之外的for。正如您在日常工作的顶部所看到的,我在发生问题的else中发表了评论。

问题在于,例如,如果用户键入sipnote我建议zipnote并且他输入y意味着他想要执行建议的命令。该命令被执行,它返回到整个例程的顶部,但它打印出来:

“Ingrese su comando”(“输入你的命令”),然后是“Quizo decir [y / n]”(“你的意思是”),它位于for外观内,要求用户选择其中一位候选人。

我不知道为什么会这样。我想要发生的是选择候选人,执行它,然后返回到顶部并重新开始。

很抱歉这个问题很长而且英文不好,这不是我的母语:P

int main()
{
    cout << "comienza rutina" < <endl;
    while(1)
    {
        cout << "entra a while" << endl;
        // First, load the commands from /usr/bin into memory and save them
        // in a vector.
        string directorio = string("/usr/bin/");
        vector<string> files = vector<string>();
        conseguirComandos(directorio,files);

        char path[80];
        char comando[80];        
        char delims[] = " ";
        char *result = NULL;

        char *argument[10];
        int i = 0;
        int k = 0;
        int child_pid,child_status; 

        int dist_hamming = 0;
        vector<string> candidatos = vector<string>();
        char resp[1];

        strcpy (path,"/usr/bin/");

        // "Enter your command."
        cout << "Ingrese su comando" << endl;
        fgets(comando,80,stdin);
        quitar_espacio(comando); 

        if (existe_comando(comando, files) == true)
        {
            result = strtok(comando, delims);

            // Split the user's command on spaces and store each word individually
            // in the argument array.  The system call execv receives the array of
            // char pointers as its second argument.
            while (result != NULL) {
                argument[i] = result;
                i++;
                result = strtok( NULL, delims );
            }

            unir_path_comando(path,argument);
            argument[i] = (char*)0; // Last element must be char *NULL, per execv docs

            char *direccion;
            direccion = path;

            if ((child_pid = fork()) != 0)
            {
                // "Parent is waiting"
                cout << "Padre espera" << endl;
                wait(&child_status);
            } else {    
                // Child process executes the user's command
                cout << "Hijo ejecuta" << endl;
                execv(path, argument);
                //exit(1);
            }
        }
        else // problem is in this section
        {
            int indice = 0;
            int condicion = 0;
            int size_cadena = 0;
            string comando_ejecutar;
            for (int i = 0; i < files.size(); i++)
            {
                if (hamming(comando, files[i]) <= 1)
                {
                    // cout << "candidato: " << files[i] << endl;
                    candidatos.push_back(files[i]);
                }
            }

        if (candidatos.size()!=0)
        {
            for (int i = 0; i < candidatos.size(); i++)
            {
                cout << "Quizo decir: " << candidatos[i] << " " << "[Y/N]"<<endl;
                scanf("%s", resp);

                if (resp[0] == 'Y' || resp[0] == 'y')
                {
                    indice = i;
                    break;
                }
            }

            // Length of the string containing the suggested command.
            size_cadena = candidatos[indice].length();
            // Store a pointer to the command to execute.
            comando_ejecutar = candidatos[indice];
            // Copy the selected command to a string.
            int m = 0;
            for (int j = 0; j < size_cadena; j++)
            {
                m++;
                comando[j] = comando_ejecutar[j];
            }
            comando[m] = 0;

            result = strtok( comando, delims );         

            //se hace un split al comando ingresado por el usuario como delimitador--> " ". Con el fin de tener cada argumento
            //en una casilla distina en el arreglo argument. Ya que el system call execv recibe como segundo parametro un arreglo 
            //de apuntadores a chars conteniendo los parametros del comando.
            int z = 0;
            while( result != NULL ) {
                argument[z] = result;
                z++;
                result = strtok( NULL, delims );
            }
        // Docs say the final argument to execv must be NULL.
        argument[z] = (char*)0;
        strcpy (path,"/usr/bin/");
        unir_path_comando(path,argument);
        char *direccion;
        direccion = path;

        if ((child_pid = fork()) != 0)
        {
            // "Parent is waiting"
            cout<<"Padre espera"<<endl;
            wait(&child_status);
        }
        else
        {   
            // Child executes the user's command.
            cout<<"Hijo ejecuta"<<endl;
            execv (path, argument);
            //exit(1);
        }
        }
        else
        {
            // No candidates to suggest.
            cout << "No tengo nada que mostrar" << endl;
        }
    }   
}
return 0;
}

1 个答案:

答案 0 :(得分:1)

scanf("%s",resp)从stdin读取,直到用户输入空格。

如果用户输入Y<enter>,则scanf会读取Y,但不会读取<enter>

当您返回循环顶部时,调用fgets(comando,80,stdin),它会立即读取<enter>留下的scanf并返回一个空字符串。空字符串不是有效命令,因此您再次提示Quizo decir [y/n]

如果您将scanf替换为fgets,它应该可以正常工作。