问题
My application forks a child, the child execls a new program, the parent writes to it, and then reads back from the child after the child performs some work. When monitoring the read end of the pipe, the program still waits for the child. I'm currently not writing back to the parent, so it intentionally would block. Below is the code (the write_to() function closes the unused parts of the pipe in the function):
pid_t leaf_proc;
int rv = 0;
int w_pfd[2];
int r_pfd[2];
if(pipe(w_pfd) == -1 || pipe(r_pfd) == -1){
printf("Failed to pipe. Goodbye.\n");
exit(0);
}
if((leaf_proc = fork()) < 0){
printf("Error: %s\n",strerror(errno));
exit(0);
}else if(leaf_proc == 0){
/***Child to be execl()'d***/
rv = execl("Some program");
if(rv < 0){
printf("Error: %s\n",strerror(errno));
exit(0);
}
}else{
/***Parent***/
write_to(par_info,w_pfd);
fd_set read_set;
//struct timeval tv;
//tv.tv_sec = 5;
//tv.tv_usec = 0;
FD_ZERO(&read_set);
FD_SET(r_pfd[0], &read_set);
rv = select(r_pfd[0]+1,&read_set,NULL,NULL,&tv);
printf("set?: %d\n",rv);
}
When running this, the program still hangs at the select statement (last printf is never reached), but if I add timeout info, the program continues after 5 seconds. First of all, am I using select correctly? And second, while this may not be blocking (in the sense that the parent process won't be interrupted by the kernel, doesn't it still result in the outcome (process hanging until something is ready)?
回答1:
You have to close the unused parts of the pipe in both the child and in the parent process.
After terminating the write fd of the pipe will be closed in the child process, but in the parent it is still open, so your select
will patiently wait for data....
来源:https://stackoverflow.com/questions/16005717/select-still-blocks-read-from-pipe