0

I want to write a process id to file whenever start my program, so I wrote this code, but this code write pid to file whenever stop the process.

from multiprocessing import Process
from os import getpid


def f():
    file = open('udp.pid', 'w')
    file.write(str(getpid()))
    file.close()
    while True:
        # a socket infinity loop
        pass

if __name__ == '__main__':
    p = Process(target=f,)
    p.start()

how to write pid to file in multiprocess?

UPDATE:

I use python 3.4 on windows 8.1

Foad Tahmasebi
  • 1,333
  • 4
  • 16
  • 33

1 Answers1

1

I think using multiprocess or not does not matter. It just about write!

open(name[, mode[, buffering]])

in https://docs.python.org/2/library/functions.html

The optional buffering argument specifies the file’s desired buffer size: 0 means unbuffered, 1 means line buffered, any other positive value means use a buffer of (approximately) that size (in bytes).

change your code

file = open('udp.pid', 'w')

to

file = open('udp.pid', 'wb', 0)
han058
  • 908
  • 8
  • 19
  • I tested it and got this error "ValueError: can't have unbuffered text I/O" – Foad Tahmasebi Jun 23 '15 at 05:18
  • nothing happened !, I use python-3.4, I change 'w' to 'wb', and "file.write(str(getpid()))" to "file.write(str(getpid()).encode('utf-8))" but nothing changed, the program write pid to file after end process! – Foad Tahmasebi Jun 23 '15 at 05:29
  • I tested the code on OS X. It works! Event your code wrote pid immediatley what you expected. – han058 Jun 23 '15 at 05:58
  • Please refer to this page, http://stackoverflow.com/questions/18194374/default-buffer-size-for-a-file – han058 Jun 23 '15 at 06:02
  • Why use binary mode when writing a simple string? –  Jun 23 '15 at 06:14
  • If it's about buffering, `f.close()` should also flush the file, so any buffer should be written to file. –  Jun 23 '15 at 06:15
  • Thank you @han058, after a lot of test finally I found problem, string written to file successfully, a problem was on my IDE, it doesn't show change until end of program. I'm sorry for that and very thanks to you and your information. – Foad Tahmasebi Jun 23 '15 at 06:24
  • @Evert You are absolutely right! I just tell the explicit thing about buffering. and my pleasure. Arshen – han058 Jun 24 '15 at 01:47