<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 async def serve(self) -> None: """ Write pidfile to sentinel directory if need be, and wait for sentinels to shut down or build revocation registry and tails file. """


        LOGGER.debug('RevRegBuilder.serve >>>')

        assert self.external

        file_pid = join(self._dir_tails_sentinel, '.pid')
        if isfile(file_pid):
            with open(file_pid, 'r') as fh_pid:
                pid = int(fh_pid.read())
            try:
                kill(pid, 0)
            except ProcessLookupError:
                remove(file_pid)
                LOGGER.info('RevRegBuilder removed derelict .pid file')
            except PermissionError:
                LOGGER.info('RevRegBuilder process already running with pid %s: exiting', pid)
                LOGGER.debug('RevRegBuilder.serve <<<')
                return
            else:
                LOGGER.info('RevRegBuilder process already running with pid %s: exiting', pid)
                LOGGER.debug('RevRegBuilder.serve <<<')
                return

        pid = getpid()
        with open(file_pid, 'w') as pid_fh:
            print(str(pid), file=pid_fh)

        file_stop = join(self._dir_tails_sentinel, '.stop')

        while True:
            if isfile(file_stop):  # stop now, pick up any pending tasks next invocation
                remove(file_stop)
                remove(file_pid)
                break

            p_pending = [join(self._dir_tails_sentinel, d) for d in listdir(self._dir_tails_sentinel)
                if isdir(join(self._dir_tails_sentinel, d))]
            p_pending = [p for p in p_pending if [s for s in listdir(p) if s.startswith('.')]]  # size marker
            if p_pending:
                pdir = basename(p_pending[0])
                rr_id = pdir
                rr_size = int([s for s in listdir(p_pending[0]) if s.startswith('.')][0][1:])
                open(join(p_pending[0], '.in-progress'), 'w').close()
                await self.create_rev_reg(rr_id, rr_size or None)
                rmtree(p_pending[0])
            await asyncio.sleep(1)

        LOGGER.debug('RevRegBuilder.serve <<<')