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?