When do you use "if ( a = b )"? (was Re: Funny mistake)
Jeff Anton
jeff at Ingres.COM
Wed Mar 20 06:33:40 AEST 1991
Consider:
if (tmp = *wakeup_pid) {
kill(tmp, SIGALRM);
*wakeup_pid = 0;
}
wakeup_pid is in shared memory. Several programs may run this code
segment at once. If it were written like:
if (*wakeup_pid) {
kill(*wakeup_pid, SIGALRM);
*wakeup_pid = 0;
}
Then there is a race condition where the loser process might call
kill(0, SIGALRM) which will be very nasty as it kills the current
process group.
Of course you could write this like:
tmp = *wakeup_pid;
if (tmp) {
kill(tmp, SIGALRM);
*wakeup_pid = 0;
}
But the separation of the assignment and the if invites new code
between the two which will increase the likelyhood of race conditions.
There is no side effect in the assignment in the if in this case unless
you consider any shared memory access to have side effects.
Jeff Anton
(p.s. Semaphores would be a safer way to deal with this)
(p.p.s. All such code which has such complex behavior but reads simply
should have a comment describing the complexities)
More information about the Comp.lang.c
mailing list