Question

I am trying to implement my own shell,there are many things not working in it but for now i'm trying to solve the first error. When my shell is running and i enter exit as the first command,it works fine,however,when i enter exit as the second input i should write exit an extra time for it to exit my shell,if i enter it as the 3rd command,i have to enter it 2 extra times,and so on. Here is my code.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{

    int argumentsnum;
    int status;

    char *arguments[30];
    char *temp;
    int processes_count=0;

    printf("My Shell\n");
    while (1)
    {
        char input[60];

        printf("Enter command\n");
        while (fgets(input, sizeof(input), stdin) == NULL)
        {
            printf("Enter command \n");
        } /*end whileloop*/

        for (argumentsnum = 0; argumentsnum < 31; argumentsnum++)
        {
            temp = strtok(input, " \t\n");
            if (temp != NULL)
            {
                arguments[argumentsnum] = temp;
            } /*endif*/

        } /*end forloop*/
        if (strcmp(arguments[0], "exit") == 0)
        {
            printf("Exiting shell\n");
            int i;
            For(i=0;i<processes_count;i++){
            exit(0);
          }
        } /*endif*/
        pid_t id = fork();
        processes_count++;
        if (id == -1)
        {
            perror("Grab your own fork :@ \n");
            exit(1);
        } /*endif*/
        else if (id == 0)
        {
            execvp(arguments[0], arguments);
        } /*endelse*/
        else
        {

            wait(&status);
        }
    } /*end while(1)*/

} /*endmain*/
Was it helpful?

Solution

execvp(arguments[0], arguments);

You need to do something if this call fails. If execvp fails because you passed it a bad command, the child process will continue onward. That means the child will process the next command, rather than the parent. The parent will be stuck in its wait() call, waiting for the child to terminate.

execvp(arguments[0], arguments);
perror("execvp");
_Exit(1);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top