my code doesn't execute after first command?

90 views Asked by At

INPUT

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

OUTPUT

Only first /bin/ls

I want to know why it doesn't execute other commands? I used strtok to split string input as i understand echo gives input as string seperated by \n.

I have tried to execute after tokenizing each delimiter, it also gave same output

#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);
}
1

There are 1 answers

6
Mathieu On

Your problem comes from buff that can contain extra spaces before or after the program you want to run.

strtok can be used to remove the characters you don't want:

while (1)
{
    size = getline(&buff, &len, stdin);
    if (size <1)
    {
        exit(0);
    }

    // extract first sequence of non-spaces characters for buff
    token = strtok(buff, " \t\n");

    if(*token == 0) {
        // empty line, go next line
        continue;
    }

    kiddo = fork();
    if (kiddo == -1)
        printf("Process error!\n");
    if (kiddo == 0)
    {

        printf("token(child): '%s'\n", token);
        // here you can call "arg[xx] = strtok(NULL, " \t\n");" to get the arguments
        execve(token, arg, environ);
        printf("execution of '%s' failed\n", token);
        return (1);
    }
    else
    {
        wait(&stat);
    }
}