Reputation: 53
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);
}
Upvotes: 2
Views: 974
Reputation: 311008
When child write(), will parent select() detects and return, even though the child is still writing (i.e. write() blocking not yet return) ?
As soon as there is data in the receiver's socket receive buffer, the socket becomes readable. If you're selecting on that socket for readability, select() will return. Could be as little as one byte received.
If child is doing write(), while parent read(), would it possibly cause parent to read incomplete message?
There is no such thing as a message in TCP. The parent can always read less data than it requested. What the child is doing at the time is irrelevant.
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.
That's not the correct way to use multiplexed I/O. The receiver should read, and if the data is incomplete it should return to the select loop and wait for another read event, do another read, etc., until the data is complete. Note that an incomplete read can happen when reading the count word as well as when reading the data.
Upvotes: 2