| 51 | |
| 52 | |
| 53 | def write_pid_file(pid_file, pid): |
| 54 | import fcntl |
| 55 | import stat |
| 56 | |
| 57 | try: |
| 58 | fd = os.open(pid_file, os.O_RDWR | os.O_CREAT, |
| 59 | stat.S_IRUSR | stat.S_IWUSR) |
| 60 | except OSError as e: |
| 61 | shell.print_exception(e) |
| 62 | return -1 |
| 63 | flags = fcntl.fcntl(fd, fcntl.F_GETFD) |
| 64 | assert flags != -1 |
| 65 | flags |= fcntl.FD_CLOEXEC |
| 66 | r = fcntl.fcntl(fd, fcntl.F_SETFD, flags) |
| 67 | assert r != -1 |
| 68 | # There is no platform independent way to implement fcntl(fd, F_SETLK, &fl) |
| 69 | # via fcntl.fcntl. So use lockf instead |
| 70 | try: |
| 71 | fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET) |
| 72 | except IOError: |
| 73 | r = os.read(fd, 32) |
| 74 | if r: |
| 75 | logging.error('already started at pid %s' % common.to_str(r)) |
| 76 | else: |
| 77 | logging.error('already started') |
| 78 | os.close(fd) |
| 79 | return -1 |
| 80 | os.ftruncate(fd, 0) |
| 81 | os.write(fd, common.to_bytes(str(pid))) |
| 82 | return 0 |
| 83 | |
| 84 | |
| 85 | def freopen(f, mode, stream): |