Foad Tahmasebi
Foad Tahmasebi

Reputation: 1352

how to write to file in multiprocess in python

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

Upvotes: 0

Views: 1050

Answers (1)

han058
han058

Reputation: 908

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)

Upvotes: 1

Related Questions