Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

934 Solutions to Selected Exercises Appendix C


#include <poll.h>
void
sleep_us(unsigned int nusecs)
{
struct pollfd dummy;
int timeout;
if ((timeout = nusecs / 1000) <= 0)
timeout = 1;
poll(&dummy, 0, timeout);
}

Figure C.17 Implementation ofsleep_ususingpoll

As the BSD usleep( 3 ) manual page states, usleep uses the nanosleep
function, which doesn’t interferewith timers set by the calling process.

14.6 No. What we would like to do is haveTELL_WAITcreate a temporary file and
use 1 byte for the parent’s lock and 1 byte for the child’s lock. WAIT_CHILD
would have the parent wait to obtain a lock on the child’s byte, and
TELL_PARENTwould have the child release the lock on the child’s byte. The
problem, however,isthat callingforkreleases all the locks in the child, so the
child can’t start offwith any locks of its own.
14.7 Asolution is shown in FigureC.18.
#include "apue.h"
#include <fcntl.h>
int
main(void)
{
int i, n;
int fd[2];
if (pipe(fd) < 0)
err_sys("pipe error");
set_fl(fd[1], O_NONBLOCK);
/* write 1 byte at a time until pipe is full */
for (n = 0; ; n++) {
if ((i = write(fd[1], "a", 1)) != 1) {
printf("write ret %d, ", i);
break;
}
}
printf("pipe capacity = %d\n", n);
exit(0);
}

Figure C.18 Calculation of pipe capacity using nonblocking writes
Free download pdf