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

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

8 Comments

I tested it and got this error "ValueError: can't have unbuffered text I/O"
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!
I tested the code on OS X. It works! Event your code wrote pid immediatley what you expected.
Please refer to this page, stackoverflow.com/questions/18194374/…
Why use binary mode when writing a simple string?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.