1

I am implementing a command line interpreter as a university homework assignment. I get the string of commands and then I have to fork and execute the commands in the child proccess. Here is a sample of my code:

do
{
    if (argc == 1)
    {
        do
        {
            do
            {   
                printf("prompt>> ");
                line = get_string();
            }while(strcmp(line, "") == 0 || line[0] == ';');

        if ( (pid = fork()) < 0 )
        {
            perror("error in forking.");
            exit(1);
        }
        else if (pid == 0)
        {
            // execute the commands with format: cmd1 ; cmd2 ; cmd3
            line_1 = strtok(line, NULL);
            if ( strcmp(line_1, "quit")
            {
                flag = 1;
            }

        }
        else
        {
            printf("...mother proccess...\n");
        }
        while ( (wpid = wait(&stat)) > 0)
    }while(status);
}
}while(something);

If I have a quit command in the commands format cmd1 ; cmd2; cmd3, I have to execute all the command and then exit the programm independent of where the quit command has been placed in the command's format. I have managed to execute all the commands and set the flag variable to 1 if I find quit. Problem is I cannot exit my program if flag == 1 after execution of all the commands has finished. I tried by send a SIGTERM signal from child with the parent's id but id didn't work. How could I do that ?

5
  • 3
    Let the mother process parse commands, and only then fork Commented Jan 3, 2018 at 14:47
  • Normally you exit your program by calling exit. Have you tried that? Are you sure the flag is set? if ( strcmp(line, "quit") doesn't seem to be formatted correctly and may not do what you think it should do. Please don't type your code when posting questions. Copy and paste from actual buildable code instead. Commented Jan 3, 2018 at 14:49
  • I've put a printf statement inside the if-clase checking for quit and checked that it gets it when quit command is placed. My actual code is too many lines that's why I tried to shrink it. Commented Jan 3, 2018 at 14:51
  • 1
    It's OK to shrink your code but it's not OK to maim it in process. Please produce a minimal reproducible example. Commented Jan 3, 2018 at 14:55
  • wouldn't you rather want strcmp(line_1 ...? or strstr(line, "quit")? Commented Jan 3, 2018 at 15:02

1 Answer 1

1

You need to check if quit is present in the parent process. You can then fork and use wait() in order to wait your child proccess to terminate and then exited normally. Or even fork and exit directly.

Sign up to request clarification or add additional context in comments.

1 Comment

Checking if quit is present in the mother proccess did the job for me!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.