我的代码在第一个命令后没有执行?

问题描述 投票:0回答:1

输入

echo "/bin/ls
     /bin/ls
/bin/ls
   /bin/ls     " | ./hsh

输出

仅第一个 /bin/ls

我想知道为什么它不执行其他命令? 我使用 strtok 来分割字符串输入,因为我理解 echo 将输入作为字符串分隔 .

我尝试在标记每个分隔符后执行,它也给出了相同的输出

#include "O_X.h"

/**
 * main - program
 * Return: 0 on success, -1 on fail
 */
char **environ;

int main(void)
{
    char *buff = NULL, *token = NULL;
    int size = 1, kiddo = 0, stat = 0;
    char *arg[] = {"" ,NULL};
    size_t len = 33;
    while (1)
    {
        size = getline(&buff, &len, stdin);
        if (size == -1)
        {
            free(buff);
            exit(0);
        }
        else if (buff == NULL)
            free(buff);
/*      else if (buff[size - 1] == '\n')
            buff[size - 1] = '\0';*/

        token = strtok(buff, "\n");
        while (token != NULL)
        {
            token = strtok(NULL, "\n");
        }


        kiddo = fork();
        if (kiddo == -1)
            printf("Process error!\n");
        if (kiddo == 0)
        {
            if (buff[0] != '/')
              buff++;
                execve(buff, arg, environ);
            return (0);
        }
        else
        {
            wait(&stat);
        }
    }
    return (0);
}
c shell systems-programming
1个回答
0
投票

仅执行以“/”开头的程序的代码不完整:您转到

buff
(
buff++
) 中的下一个字符,但您不会尝试再次检查是否可以运行该命令。

你应该有一个循环来测试是否在

/
中找到了
buff
,如果找不到就放弃

kiddo = fork();
if (kiddo == -1)
{ // curly brackets are your friends, invite them in you code
    printf("Process error!\n");
}

if (kiddo == 0)
{
    // first, we check that buff is not null
    while(*buff) {

        // display what we test
        printf("buff: '%s'\n", buff);

        // test if buff start with '/'
        if (buff[0] != '/'){
            // if not, go next char   
            buff++;
            // and go to while loop start
            continue;
        }
        execve(buff, arg, environ);
        // we will reach this point only if execve failed, so trace it
        printf("execution of '%s' failed\n", buff);
        return (1);
    }
    // if buff is null, return a 2 error (hence, in parent, you'll be able to know why the failure)
    printf("no '/' found in buff\n");
    return (2);
}
else
{
    wait(&stat);
}
© www.soinside.com 2019 - 2024. All rights reserved.