Reputation: 93
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;}
Upvotes: 0
Views: 1595
Reputation: 5463
You have to flush stdout
before calling wait()
.
Your program was working before without the wait()
since an implicit flush was done when the parent process exit.
Upvotes: 0
Reputation: 1
You should read a good book on advanced unix programming, learn to use multiplexing calls like poll(2) (or select
, or pselect
, or ppoll
), possibly learn to use SIGCHLD. Be careful, a signal handler can call only a very limited set of functions (the async-safe one) and should often set a volatile sig_atomic_t
variable.
Upvotes: 0
Reputation: 182769
You forgot to close fd[1]
after the dup2
call in the parent. Also, you need to write some character that will cause scanf
to realize it has read the end of the string. Closing stdout after calling puts
would be one way.
Upvotes: 1