| 19 | self.pid = None |
| 20 | |
| 21 | def create(self, pid): |
| 22 | oldpid = self.validate() |
| 23 | if oldpid: |
| 24 | if oldpid == os.getpid(): |
| 25 | return |
| 26 | msg = "Already running on PID %s (or pid file '%s' is stale)" |
| 27 | raise RuntimeError(msg % (oldpid, self.fname)) |
| 28 | |
| 29 | self.pid = pid |
| 30 | |
| 31 | # Write pidfile |
| 32 | fdir = os.path.dirname(self.fname) |
| 33 | if fdir and not os.path.isdir(fdir): |
| 34 | raise RuntimeError("%s doesn't exist. Can't create pidfile." % fdir) |
| 35 | fd, fname = tempfile.mkstemp(dir=fdir) |
| 36 | try: |
| 37 | os.write(fd, ("%s\n" % self.pid).encode('utf-8')) |
| 38 | if self.fname: |
| 39 | os.rename(fname, self.fname) |
| 40 | else: |
| 41 | self.fname = fname |
| 42 | finally: |
| 43 | os.close(fd) |
| 44 | |
| 45 | # set permissions to -rw-r--r-- |
| 46 | os.chmod(self.fname, 420) |
| 47 | |
| 48 | def rename(self, path): |
| 49 | self.unlink() |