Reputation: 1065
I'm studying C, and I've a doubt regarding while. In an exercise I've:
while(1){
while((sockacc = accept(ds_sock,&client,&length)) == -1);
--other instructions--
}
Can anyone tell me which is the function of the second while? I mean, I know what the accept call is used for. I don't understand why use a while condition if there isn't anything in the body.
Upvotes: 0
Views: 1468
Reputation: 659994
Take a step back. Remember that the meaning of
while(c) s;
is just a short way of writing:
CONTINUE:
if (c)
goto BODY;
else
goto BREAK;
BODY:
s;
goto CONTINUE;
BREAK: ;
and of course break;
and continue;
are goto BREAK;
and goto CONTINUE;
. Loops aren't magical; they're just a short and pleasant way of writing a bunch of goto
statements.
So your program:
while(1){
while((sockacc = accept(ds_sock,&client,&length)) == -1);
--other instructions--
}
is just a nicer way to write:
OUTER_CONTINUE:
if (1)
goto OUTER_BODY;
else
goto OUTER_BREAK;
OUTER_BODY:
{
INNER_CONTINUE:
if ((sockacc = accept(ds_sock,&client,&length)) == -1)
goto INNER_BODY;
else
goto INNER_BREAK;
INNER_BODY:
;
goto INNER_CONTINUE;
INNER_BREAK: ;
--other instructions--
}
goto OUTER_CONTINUE;
OUTER_BREAK: ;
Upvotes: 5
Reputation: 753575
One of the reasons why accept()
can return a failure (-1) is EINTR (interrupted system call). The inner loop in this code retries accept()
if it returns an error EINTR, or indeed any other error since it does not test the value of errno
in the inner loop body. This could be a performance problem if the error is EBADF (bad file descriptor, indicating that socket file descriptor either isn't a socket file descriptor or has somehow been destroyed). Normally, you see a test in the body of the loop to ensure that the error is one of the limited set that the code expects.
Upvotes: 1
Reputation: 2273
You could rewrite this whole code as:
while(1){
do {
sockacc = accept(ds_sock,&client,&length);
}
while(sockacc == -1);
--other instructions--
}
The part in the while statement is just executed every loop iteration, and itself determines if the loop terminates.
Upvotes: 4