I'm trying to write an application which consists of a Parent multiplexing inputs from different Child, using select(), write() and read() with Pipe.
Would like to seek advice for a few things below:
When child write(), will parent select() detects and return, even though the child is still writing (i.e. write() blocking not yet return) ?
If child is doing write(), while parent read(), would it possibly cause parent to read incomplete message?
Is "protection" codes necessary for Q1 & Q2?
e.g. Define 4-bytes header to indicate message length. Parent read() first 4-bytes to examine message length, then loop and read() until exactly the same length is got.
Just for illustration, below are the parent & child code segment. I'm asking as to see if varying buf_len in child will cause issue to parent.
Parent code segment
int MAX_LENGTH=10000;
char buf[MAX_LENGTH];
int pipeFd[2];
pipe(pipeFd);
//fork child code and create pipe codes skipped..
fd_set pipeSet;
int r, nbytes;
close(pipeFd[1]);
while (1){
FD_ZERO(&pipeSet);
FD_SET(pipeFd[0], &pipeSet);
memset(buf, 0, MAX_LENGTH);
r=select(pipeFd[0] + 1, &pipeSet, NULL, NULL, NULL);
if(FD_ISSET(pipeFd[0], &pipeSet))
nbytes=read(pipeFd, buf, MAX_LENGTH);
}
Child code segement
close(pipeFd[0]);
int buf_len;
while (1){
memset(buf, 0, MAX_LENGTH);
//codes to get data from different means depending on child ID
//e.g. msgget() from msg queue, user input... etc.
//length of data varies
write(pipeFd[1], buf, buf_len);
}