2017-02-07 6 views
0

os.fork와 with의 동작이 어떻게 든 파이썬 사양에 정의되어 있고 os.fork와 함께 사용해야하는지를 알고 싶습니다. 내가 할 경우with python with with os.fork

는, 예를 들면 :

> python3 foo.py 
27023 
/tmp/tmpg1typbde 
0 
/tmp/tmpg1typbde 
Traceback (most recent call last): 
    File "foo.py", line 6, in <module> 
    print(dir) 
    File "/usr/lib/python3.4/tempfile.py", line 824, in __exit__ 
    self.cleanup() 
    File "/usr/lib/python3.4/tempfile.py", line 828, in cleanup 
    _rmtree(self.name) 
    File "/usr/lib/python3.4/shutil.py", line 467, in rmtree 
    onerror(os.rmdir, path, sys.exc_info()) 
    File "/usr/lib/python3.4/shutil.py", line 465, in rmtree 
    os.rmdir(path) 
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/tmpg1typbde' 

궁금 해요 : :

    import tempfile 
    import os 
    with tempfile.TemporaryDirectory() as dir: 
        pid = os.fork() 
        print(pid) 
        print(dir) 
    

    는 그런 다음 두 번 TemporaryDirectory을 삭제하는 순진한 행동을 사용하는 것으로 보인다

  1. 동작이 실제로 정의 된 경우
  2. 어떻게하면 좋을까요? 두 프로세스 사이의 임시 디렉토리입니다.
+1

아마도 자식 프로세스에서''os._exit()''를 사용하여 정리 작업을 수행하지 않고 종료 할 수 있습니다. 이것은 정리가 필요한 모든 것이 상위 프로세스와 공유된다고 가정합니다. – jasonharper

+0

실제 답변이 아니지만 그 수준으로 나아가는 것이 정말로 필요합니까? 일반적으로 특정 작업 (예 : 특정 작업)을 위해 파이썬에서 여러 프로세스를 관리하는 더 많은 맞춤형 메커니즘이 있습니다. 다중 처리. – languitar

+0

@languitar 확실하지 않습니다. 지금 작업하고있는 코드는 제 테스트 소송입니다. 코드의 목표는 프로그램 시작시 잠금 코드에 경주 대회가 있는지 테스트하려고 시도하는 내 프로그램의 여러 버전을 생성하는 것입니다. 그래서 나는 정말로 사태가 동시에 일어나길 바란다.). 하지만 아마 일반적으로, os.fork는 파이썬에서 할 수있는 최선의 일이 아닙니다. – timthelion

답변

0

더러워진 오래된 방법이 사용되지 않습니다.

> cat foo.py 
import tempfile 
import os 
import shutil 
temp_dir = tempfile.mkdtemp(prefix="foo") 
pid = os.fork() 
print(pid) 
print(temp_dir) 
if not pid: 
    input("pid: %s\nPress enter to continue."%pid) 
if pid: 
    print("pid: %s\nWaiting for other pid to exit."%pid) 
    os.waitpid(pid,0) 
    shutil.rmtree(temp_dir) 
    print("Bye") 

.

> python3 foo.py 
27510 
/tmp/foopyvuuwjw 
pid: 27510 
Waiting for other pid to exit. 
0 
/tmp/foopyvuuwjw 
pid: 0 
Press enter to continue. 
Bye