本文介紹Python的os包中有查詢和修改進程資訊的函數,Python的這些工具符合Linux系統的相關概念,所以可以協助理解Linux體系。
1. 進程資訊
os包中相關函數如下:
uname() 返回作業系統相關資訊,類似於Linux上的uname命令。
umask() 設定該進程建立檔案時的許可權mask,類似於Linux上的umask命令。
get*() 查詢 (*由以下代替)
uid, euid, resuid, gid, egid, resgid :許可權相關,其中resuid主要用來返回saved UID。相關介紹見Linux使用者與“最小許可權”原則
pid, pgid, ppid, sid :進程相關。相關介紹見Linux進程關係
put*() 設定 (*由以下代替)
euid, egid: 用於更改euid,egid。
uid, gid : 改變進程的uid, gid。只有super user才有權改變進程uid和gid (意味著要以$sudo python的方式運行Python)。
pgid, sid : 改變進程所在的進程組(process group)和會話(session)。
getenviron():獲得進程的環境變數
setenviron():更改進程的環境變數
例1,進程的real UID和real GID, #注釋後面是結果
#!/usr/bin/env python# -*- coding: utf-8 -*-'''@author: homer@see: ithomer.net'''import osprint(os.getuid()) # 1000print(os.getpid()) # 9047print(os.getppid()) # 6829print(os.getgid()) # 1000print(os.getgroups()) # [4, 24, 27, 30, 46, 109, 124, 1000]print(os.getenv("JAVA_HOME", )) # /home/homer/eclipse/jdk1.6.0_22
將上面的程式儲存為py_id.py檔案,分別用$python py_id.py和$sudo python py_id.py看一下運行結果
2. 有關saved UID和saved GID
saved UID和saved GID很難如同我們在Linux使用者與“最小許可權”原則中描述的那樣在Python程式工作。原因在於,當我們寫一個Python指令碼後,我們實際啟動並執行是python這個解譯器,而不是python指令檔 (而C語言則是直接運行由C語言編譯成的執行檔案)。我們必須更改python這個執行檔案本身的許可權來運用saved UID機制,然而這麼做又是異常危險的。
比如說,我們的python執行檔案為/usr/bin/python (你可以通過$which python獲知)
我們先看一下
$ls -l /usr/bin/python
的結果:
-rwxr-xr-x root root
我們修改許可權以設定set UID和set GID位 (參考Linux使用者與“最小許可權”原則)
$sudo chmod 6755 /usr/bin/python
/usr/bin/python的許可權成為:
-rwsr-sr-x root root
隨後,我們運行檔案下面test.py檔案,這個檔案可以是由普通使用者vamei所有:
import osprint(os.getresuid())
我們得到結果:
(1000, 0, 0)
上面分別是UID,EUID,saved UID。我們只用執行一個由普通使用者擁有的python指令碼,就可以得到super user的許可權。所以,這樣做是極度危險的,我們相當於交出了系統的保護系統。想像一下Python強大的功能,別人現在可以用這些強大的功能作為攻擊你的武器了。使用下面命令來恢複到從前:
$sudo chmod 0755 /usr/bin/python
總結:
get*, set*
umask(), uname()
Python 多進程
1. threading 和 multiprocessing
multiprocessing包是Python中的多流程管理組件。與threading.Thread類似,它可以利用multiprocessing.Process對象來建立一個進程。該進程可以運行在Python程式內部編寫的函數。該Process對象與Thread對象的用法相同,也有start(), run(), join()的方法。此外multiprocessing包中也有Lock/Event/Semaphore/Condition類 (這些對象可以像多線程那樣,通過參數傳遞給各個進程),用以同步進程,其用法與threading包中的同名類一致。所以,multiprocessing的很大一部份與threading使用同一套API,只不過換到了多進程的情境。
但在使用這些共用API的時候,我們要注意以下幾點: 在UNIX平台上,當某個進程終結之後,該進程需要被其父進程調用wait,否則進程成為殭屍進程(Zombie)。所以,有必要對每個Process對象調用join()方法 (實際上等同於wait)。對於多線程來說,由於只有一個進程,所以不存在此必要性。 multiprocessing提供了threading包中沒有的IPC(比如Pipe和Queue),效率上更高。應優先考慮Pipe和Queue,避免使用Lock/Event/Semaphore/Condition等同步方式 (因為它們佔據的不是使用者進程的資源)。 多進程應該避免共用資源。在多線程中,我們可以比較容易地共用資源,比如使用全域變數或者傳遞參數。在多進程情況下,由於每個進程有自己獨立的記憶體空間,以上方法並不合適。此時我們可以通過共用記憶體和Manager的方法來共用資源。但這樣做提高了程式的複雜度,並因為同步的需要而降低了程式的效率。
Process.PID中儲存有PID,如果進程還沒有start(),則PID為None。
我們可以從下面的程式中看到Thread對象和Process對象在使用上的相似性與結果上的不同。各個線程和進程都做一件事:列印PID。但問題是,所有的任務在列印的時候都會向同一個標準輸出(stdout)輸出。這樣輸出的字元會混合在一起,無法閱讀。使用Lock同步,在一個任務輸出完成之後,再允許另一個任務輸出,可以避免多個任務同時向終端輸出。
#!/usr/bin/env python# -*- coding: utf-8 -*-'''@author: homer@see: ithomer.net'''import osimport threadingimport multiprocessing# worker functiondef worker(sign, lock): lock.acquire() print(sign, os.getpid()) lock.release()# Mainprint('Main:', os.getpid()) # 主進程# Multi-threadrecord = []lock = threading.Lock()for i in range(5): thread = threading.Thread(target=worker,args=('thread', lock)) thread.start() record.append(thread)for thread in record: print(thread) thread.join()# Multi-processrecord = []lock = multiprocessing.Lock()for i in range(5): process = multiprocessing.Process(target=worker,args=('process',lock)) process.start() record.append(process)for process in record: print(process) process.join()
運行結果:
('Main:', 9904)('thread', 9904)('thread', 9904)('thread', 9904)('thread'<Thread(Thread-1, stopped 140098907965184)><Thread(Thread-2, stopped 140098907965184)><Thread(Thread-3, stopped 140098899572480)><Thread(Thread-4, started 140098907965184)>, 9904)<Thread(Thread-5, started 140098899572480)>('thread', 9904)('process', 9914)('process', 9915)('proces<Process(Process-1, stopped)>s', 9916)<Process(Process-2, stopped)><Process(Process-3, started)><Process(Process-4, started)>('process', 9917)<Process(Process-5, started)>('process', 9918)
所有Thread的PID都與主程式相同,而每個Process都有一個不同的PID。
使用mutiprocessing包將Python多線程與同步中的多線程程式更改為多進程程式
2. Pipe和Queue
正如我們在Linux多線程中介紹的管道PIPE和訊息佇列message queue,在multiprocessing包中有Pipe類和Queue類來分別支援這兩種IPC機制。Pipe和Queue可以用來傳送常見的對象。
1) Pipe可以是單向(half-duplex),也可以是雙向(duplex)。我們通過mutiprocessing.Pipe(duplex=False)建立單向管道 (預設為雙向)。一個進程從PIPE一端輸入對象,然後PIPE另一端的進程接收對象。單向管道只允許管道一端的進程輸入,而雙向管道則允許從兩端輸入。
下面的程式展示了Pipe的使用:
#!/usr/bin/env python# -*- coding: utf-8 -*-'''@author: homer@see: ithomer.net'''import multiprocessing as multiprodef proc1(pipe): pipe.send('hello') print('proc1 recv:', pipe.recv())def proc2(pipe): print('proc2 recv:', pipe.recv()) pipe.send('hello, too')# Build a pipepipe = multipro.Pipe()# Pass an end of the pipe to process 2p1 = multipro.Process(target=proc1, args=(pipe[0],))# Pass the other end of the pipe to process 1p2 = multipro.Process(target=proc2, args=(pipe[1],))p1.start()p2.start()p1.join()p2.join()
運行結果:
('proc2 rec:', 'hello')
('proc1 rec:', 'hello, too')
這裡的Pipe是雙向的。
Pipe對象建立的時候,返回一個含有兩個元素的表,每個元素代表Pipe的一端(Connection對象)。我們對Pipe的某一端調用send()方法來傳送對象,在另一端使用recv()來接收。
2) Queue與Pipe相類似,都是先進先出的結構。但Queue允許多個進程放入,多個進程從隊列取出對象。Queue使用mutiprocessing.Queue(maxsize)建立,maxsize表示隊列中可以存放對象的最大數量。
下面的程式展示了Queue的使用:
#!/usr/bin/env python# -*- coding: utf-8 -*-'''@author: homer@see: ithomer.net'''import osimport multiprocessingimport time# input workerdef inputQ(queue): info = str(os.getpid()) + ' (put): ' + str(time.strftime("%Y-%m-%d__%H:%M:%S", time.localtime(time.time()))) queue.put(info)# output workerdef outputQ(queue, lock): info = queue.get() lock.acquire() print (str(os.getpid()) + '(get):' + info + "\n") lock.release() # Mainrecord1 = [] # store input processesrecord2 = [] # store output processeslock = multiprocessing.Lock() # To prevent messy printqueue = multiprocessing.Queue(3)# input processesfor i in range(10): process = multiprocessing.Process(target=inputQ, args=(queue,)) process.start() record1.append(process)# output processesfor i in range(10): process = multiprocessing.Process(target=outputQ, args=(queue, lock)) process.start() record2.append(process)for p in record1: p.join()queue.close() # No more object will come, close the queuefor p in record2: p.join()
運行結果:
10370(get):10357 (put): 2013-12-11__19:32:0910369(get):10356 (put): 2013-12-11__19:32:0910372(get):10359 (put): 2013-12-11__19:32:0910371(get):10360 (put): 2013-12-11__19:32:0910378(get):10366 (put): 2013-12-11__19:32:0910374(get):10365 (put): 2013-12-11__19:32:0910376(get):10364 (put): 2013-12-11__19:32:0910380(get):10361 (put): 2013-12-11__19:32:0910381(get):10368 (put): 2013-12-11__19:32:0910383(get):10367 (put): 2013-12-11__19:32:09
一些進程使用put()在Queue中放入字串,這個字串中包含PID和時間。另一些進程從Queue中取出,並列印自己的PID以及get()的字串。
總結:
Process, Lock, Event, Semaphore, Condition
Pipe, Queue
部落格之星評選,請投我一票:
http://vote.blog.csdn.net/blogstaritem/blogstar2013/sunboy_2050