如何解决Linux系统中出现的进程重复运行问题
更新时间:2023-10-05杩涚▼閲嶅杩愯闂绠€浠?/h4>
鍦↙inux绯荤粺涓紝杩涚▼閲嶅杩愯鏄竴涓父瑙佺殑闂銆傚湪鏌愪簺鎯呭喌涓嬶紝鎴戜滑鍙兘闇€瑕佸悓涓€杩涚▼鍦ㄥ涓疄渚嬩腑杩愯銆備絾鏄紝鍦ㄥ叾浠栨儏鍐典笅锛岃繘绋嬬殑澶氭閲嶅杩愯鍙兘浼氬鑷撮棶棰樸€備緥濡傦紝瀹冨彲鑳戒細娑堣€楄繃澶氱殑绯荤粺璧勬簮锛屽鑷存€ц兘闂锛屾垨鑰呭畠鍙兘浼氬垱寤哄啿绐佸拰绔炰簤鏉′欢銆傚湪杩欑鎯呭喌涓嬶紝浜嗚В濡備綍瑙e喅杩欎釜闂鏄潪甯搁噸瑕佺殑銆?/p>
濡備綍瑙e喅杩涚▼閲嶅杩愯闂
涓嬮潰鏄竴浜涜В鍐矻inux绯荤粺涓繘绋嬮噸澶嶈繍琛岄棶棰樼殑鍑犵甯歌鏂规硶锛?/p> 馃捇 鏂规硶涓€锛氫娇鐢╬id鏂囦欢
鎴戜滑鍙互涓鸿繘绋嬪垱寤轰竴涓猵id鏂囦欢锛屽苟鍦ㄦ瘡娆¤繍琛屾椂妫€鏌ヨpid鏂囦欢鏄惁瀛樺湪銆傚鏋減id鏂囦欢涓嶅瓨鍦紝鍒欒繘绋嬪彲浠ュ惎鍔ㄣ€傚鏋減id鏂囦欢瀛樺湪锛屽垯杩涚▼搴旇涓嶈繍琛屻€傝繖绉嶆柟娉曠‘淇濆彧鏈変竴涓繘绋嬪湪浠讳綍缁欏畾鏃跺埢杩愯銆備互涓嬫槸涓€涓畝鍗曠殑Python绀轰緥锛?/p>
import os pid_file = "/var/run/my_process.pid" if os.path.isfile(pid_file): print("Process is already running") else: with open(pid_file, "w") as f: f.write(str(os.getpid())) print("Process started")馃捇 鏂规硶浜岋細浣跨敤杩涚▼闂撮€氫俊
鍙︿竴绉嶈В鍐宠繘绋嬮噸澶嶈繍琛岄棶棰樼殑鏂规硶鏄娇鐢ㄨ繘绋嬮棿閫氫俊銆傛垜浠彲浠ヤ娇鐢ㄥ鎺ュ瓧銆佹枃浠堕攣鎴朓PC瀵硅薄绛夋満鍒舵潵杩涜閫氫俊銆傚湪杩愯杩涚▼涔嬪墠锛屾垜浠彲浠ユ鏌ラ€氫俊鏈哄埗鏄惁瀛樺湪銆傚鏋滃畠涓嶅瓨鍦紝鍒欐垜浠彲浠ヨ繍琛岃繘绋嬪苟鍒涘缓閫氫俊鏈哄埗銆傚鏋滃畠宸茬粡瀛樺湪锛屽垯杩涚▼搴旇涓嶈繍琛屻€備互涓嬫槸涓€涓狿ython绀轰緥锛屾紨绀哄浣曚娇鐢╯ocket鏉ュ疄鐜拌繘绋嬮棿閫氫俊锛?/p>
import socket import sys pid_socket = "/tmp/my_process.sock" server = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM) try: server.bind(pid_socket) except socket.error: print("Process is already running") sys.exit() print("Process started")馃捇 鏂规硶涓夛細浣跨敤shell鍛戒护妫€鏌ヨ繘绋嬬姸鎬?/strong>
鍙︿竴绉嶈В鍐宠繘绋嬮噸澶嶈繍琛岄棶棰樼殑鏂规硶鏄娇鐢╯hell鍛戒护鏉ユ鏌ヨ繘绋嬬姸鎬併€傛垜浠彲浠ヤ娇鐢╬s鍛戒护鏉ュ垪鍑哄綋鍓嶆鍦ㄨ繍琛岀殑杩涚▼锛屽苟浣跨敤grep杩囨护瑕佽繍琛岀殑杩涚▼鐨勫悕绉般€傚鏋済rep鍛戒护鏈壘鍒拌繘绋嬶紝鍒欏厑璁稿惎鍔ㄨ繘绋嬨€備互涓嬫槸涓€涓猙ash鑴氭湰绀轰緥锛?/p>
#!/bin/bash if ps -ef | grep -v grep | grep my_process > /dev/null; then echo "Process is already running" else my_process & echo "Process started" fi馃捇 鏂规硶鍥涳細浣跨敤绯荤粺鏃ュ織
鏈€鍚庝竴绉嶈В鍐宠繘绋嬮噸澶嶈繍琛岄棶棰樼殑鏂规硶鏄娇鐢ㄧ郴缁熸棩蹇椼€傛垜浠彲浠ョ紪鍐欐棩蹇楄褰曞簲鐢ㄧ▼搴忥紝瀹冨皢鍦ㄦ瘡娆¤繍琛屾椂灏嗚褰曞啓鍏ョ郴缁熸棩蹇椼€傜劧鍚庯紝鎴戜滑鍙互鍦ㄦ瘡娆″惎鍔ㄨ繘绋嬫椂妫€鏌ョ郴缁熸棩蹇楋紝浠ョ‘淇濊杩涚▼涓嶄細鍦ㄧ粰瀹氭椂闂撮噸澶嶈繍琛屻€備互涓嬫槸涓€涓狿ython绀轰緥锛?/p>
import logging import os pid_log = "/var/log/my_process.log" logging.basicConfig(filename=pid_log, level=logging.DEBUG) if "Process started" in open(pid_log).read(): print("Process is already running") else: os.system("echo 'Process started' >> " + pid_log) print("Process started")
缁撹
鍦↙inux绯荤粺涓紝瑙e喅杩涚▼閲嶅杩愯闂鍗佸垎閲嶈銆備笂杩板洓绉嶆柟娉曢兘鏈夊姪浜庤В鍐抽棶棰橈紝鍏蜂綋閫夋嫨鍝竴绉嶆柟娉曞簲鏍规嵁鍏蜂綋鎯呭喌鑰屽畾銆傛棤璁哄摢绉嶈В鍐虫柟娉曪紝閮介渶瑕佹纭紪鍐欎唬鐮侊紝骞剁粡杩囨祴璇曞拰楠岃瘉銆傜‘淇濊繘绋嬩粎鍦ㄩ渶瑕佹椂杩愯锛屽彲纭繚绯荤粺鎬ц兘鍜岀ǔ瀹氭€с€?/p>