Here is a small piece of code, the parent process write pipe and child read pipe, everything works fine before I add ‘wait()’ in parent process. I think it should be no difference, but it just stucks when I input. I’m quite new to system programming. Anyone can help with this?
int main() {
char* msg = malloc(sizeof(100));
int fd[2];
pipe(fd);
int status;
if (fork()!=0){
close(fd[0]);
dup2(fd[1],1);
scanf("%s",msg);
puts(msg);
wait(&status);
}
else {
char* buf = malloc(sizeof(100));
close(fd[1]);
dup2(fd[0],0);
scanf("%s",buf);
puts(buf);
}
return 0;}
You have to flush
stdoutbefore callingwait().Your program was working before without the
wait()since an implicit flush was done when the parent process exit.