0

I'm doing a homework and need some help with how to avoid printing duplicates when using fork() function.

The flow of my code is presumed to be as follow: menu is printed, user selects some of the options and then it creates a duplicate process using fork() to do what the option says. I'm hiding what it does on the following code and printing instead so its easier to understand:

int main() {
    int option;
    pid_t pid;
    while (option != 3) {
       printf("\nMenu:"):
       printf("\n1 browser"):
       printf("\n2 terminal"):
       printf("\n3 finish"):
       printf("\nOption:"):
       scanf("%d", &option);
       switch (option) {
           case 1:
               if ((pid = fork()) == -1) {
                    printf("error");
               } else {
                    printf("browser");
               }
               break;
           case 2:
               if ((pid = fork()) == -1) {
                    printf("error");
               } else {
                    printf("terminal");
               }
               break;
           case 3:
               break;
           default:
               break;
    }
    return 0;
}

Problem is this code prints the menu, and then when I choose some of the options, it not only does what I want, but it also prints the menu twice in the end and it should print it only one time, cause its returning to the menu after it does what it is intented to. Is there any way to avoid this?

mdweber
  • 53
  • 7

1 Answers1

2

It's not clear that fork() does anything useful for you here, unless there's some significant logic you've omitted.

If you do want to use it, though, you need to:

  1. Behave differently in the parent and child processes, by checking the value of pid. (It will be zero in the child process.)

  2. Have that child process exit() when it is done, rather than falling through into your main loop.

  3. Have the parent process use wait() or waitpid() to wait for the child process to exit before continuing with the main loop.

  • Just like you say, I'm ommitting some significant logic, but the problem can be explained by that part of code. But I'm gonna try to do as you say, thank you. – mdweber Apr 07 '19 at 02:08