c语言编程笔录

首页 >   > 笔记大全

笔记大全

如何解决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>

  • 个人微信

    工作时间

    周一至周日 9:00-21:00