my scanf
statement, in a child process, does not work properly:
int main(int argc, char **argv)
{
int operando, operatore;
pid2 = fork();
if (pid2 == 0) { // Figlio 2
printf("Inserisci due numeri: ");
scanf("%d%d", &operando, &operatore); //even though I " %d%d"...
printf("Operando is %d and operatore is %d\n", operando, operatore);
}
return 0;
}
This is the output: error
See this question for an explanation of what is happening in your program: Child process cannot read after the exiting of parent process. The most important part:
The terminal is controlled by the foreground process group. When the shell invokes the parent, it makes the parent the leader of the foreground process group. The child inherits that group and has access to the terminal.
However, when the parent exits, the shell takes back control of the terminal and becomes the leader of the foreground process group. The child is no longer in the foreground process group, so it has no access to the terminal.
To get your program to work as expected, add a wait
call in the parent process to ensure the parent process does not exit until the child process has completed thus keeping the terminal available for the child.
For example:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, char **argv)
{
int operando, operatore;
pid_t pid2 = fork();
if (pid2 == 0) { // Figlio 2
printf("Inserisci due numeri: ");
scanf("%d%d", &operando, &operatore); //even though I " %d%d"...
printf("Operando is %d and operatore is %d\n", operando, operatore);
} else if (pid2 > 0) {
wait(NULL);
}
return 0;
}
Note, some other general improvements to consider:
scanf
in particular should be checked before using the results in the printf
. Similarly the fork
return value should be checked for error.