Python 은 파일 잠 금 을 사용 하여 프로 세 스 간 동기 화 기능 을 실현 합 니 다 [fcntl 모듈 기반]
간단 한 소개
실제 응용 에서 이러한 응용 장면 이 나타 날 수 있 습 니 다. 셸 에서 실 행 된 스 크 립 트 가 일부 경쟁 자원 에 대해 보 호 를 제공 하여 충돌 이 발생 하지 않도록 하 기 를 바 랍 니 다.본 고 는 fcntl 모듈 의 파일 전체 잠 금 체 제 를 통 해 이러한 프로 세 스 간 동기 화 기능 을 실현 할 것 이다.
fcntl 시스템 함수 소개
Linux 시스템 은 파일 전체 잠 금 (flock) 과 더 작은 입자 의 기록 잠 금 (fcntl) 기능 을 제공 하 며, 바 텀 기능 은 모두 fcntl 함수 에 의 해 이 루어 집 니 다.
우선 기록 잠 금 부터 알 아 보 겠 습 니 다.기록 잠 금 은 읽 기와 쓰기 잠 금 의 확장 형식 으로 친연 관계 가 있 거나 친연 관계 가 없 는 프로 세 스 간 에 파일 의 읽 기와 쓰 기 를 공유 하 는 데 사용 할 수 있 습 니 다.잠 긴 파일 은 설명 자 를 통 해 접근 합 니 다. 잠 금 동작 을 수행 하 는 함 수 는 fcntl 입 니 다.이러한 유형의 잠 금 은 커 널 에서 유지 되 며, 숙주 표 지 는 fcntl 호출 프로 세 스 의 프로 세 스 ID 입 니 다.이 잠 금 은 같은 프로 세 스 내 다른 스 레 드 간 잠 금 이 아 닌 다른 프로 세 스 간 잠 금 에 사 용 됩 니 다.
fcntl 기록 잠 금 은 읽 기 에 도 사용 할 수 있 고 쓰기 에 도 사용 할 수 있 습 니 다. 파일 의 임의의 바이트 에 대해 서 는 최대 한 가지 유형의 자물쇠 (읽 기 자물쇠 또는 쓰기 자물쇠) 만 존재 할 수 있 습 니 다.그리고 주어진 바이트 에 여러 개의 읽 기와 쓰기 자물쇠 가 있 을 수 있 지만, 한 개의 쓰기 자물쇠 만 있 을 수 있다.
파일 을 열 고 있 는 주어진 프로 세 스 에 대해 서 는 이 파일 의 설명 자 를 닫 거나 종료 할 때 이 파일 과 연 결 된 모든 잠 금 이 삭 제 됩 니 다.자 물 쇠 는 포크 를 통 해 하위 프로 세 스 로 계승 할 수 없습니다.
NAME
fcntl - manipulate file descriptor
SYNOPSIS
#include
#include
int fcntl(int fd, int cmd, ... /* arg */ );
DESCRIPTION
fcntl() performs one of the operations described below on the open file descriptor fd. The operation is determined by cmd.
fcntl() can take an optional third argument. Whether or not this argument is required is determined by cmd. The required argument type
is indicated in parentheses after each cmd name (in most cases, the required type is int, and we identify the argument using the name
arg), or void is specified if the argument is not required.
Advisory record locking
Linux implements traditional ("process-associated") UNIX record locks, as standardized by POSIX. For a Linux-specific alternative with
better semantics, see the discussion of open file description locks below.
F_SETLK, F_SETLKW, and F_GETLK are used to acquire, release, and test for the existence of record locks (also known as byte-range, file-
segment, or file-region locks). The third argument, lock, is a pointer to a structure that has at least the following fields (in
unspecified order).
struct flock {
...
short l_type; /* Type of lock: F_RDLCK,
F_WRLCK, F_UNLCK */
short l_whence; /* How to interpret l_start:
SEEK_SET, SEEK_CUR, SEEK_END */
off_t l_start; /* Starting offset for lock */
off_t l_len; /* Number of bytes to lock */
pid_t l_pid; /* PID of process blocking our lock
(set by F_GETLK and F_OFD_GETLK) */
...
};
그 다음으로 파일 잠 금 은 Berkeley 의 Unix 에서 유래 하여 전체 파일 에 잠 금 을 채 우거 나 잠 금 을 풀 수 있 는 파일 잠 금 (file locking) 을 지원 하지만 파일 내 바이트 범위 에 잠 금 을 채 우거 나 잠 금 을 풀 수 있 는 능력 이 없습니다.
fcntl 모듈 및 파일 잠 금 기반 동기 화 기능.
Python fcntl 모듈 은 파일 설명자 기반 파일 과 I/O 제어 기능 을 제공 합 니 다.이것 은 유 닉 스 시스템 에서 fcntl () 과 ioctl () 을 호출 하 는 인터페이스 입 니 다.따라서 우 리 는 파일 잠 금 을 기반 으로 프로 세 스 동기 화 기능 을 제공 할 수 있 습 니 다.
import fcntl
class Lock(object):
def __init__(self, file_name):
self.file_name = file_name
self.handle = open(file_name, 'w')
def lock(self):
fcntl.flock(self.handle, fcntl.LOCK_EX)
def unlock(self):
fcntl.flock(self.handle, fcntl.LOCK_UN)
def __del__(self):
try:
self.handle.close()
except:
pass
활용 단어 참조
저 희 는 간단 한 장면 애플 리 케 이 션 을 만 듭 니 다. 지정 한 서버 에서 소프트웨어 버 전 을 다운로드 하고/exports/images 디 렉 터 리 로 내 려 가 야 합 니 다. 이 스 크 립 트 는 다 중 사용자 환경 에서 실 행 될 수 있 기 때 문 입 니 다.충돌 이 발생 하 기 를 원 하지 않 으 며, 이 디 렉 터 리 아래 에 만 지정 한 소프트웨어 버 전 을 저장 합 니 다.다음은 파일 잠 금 기반 참조 구현 입 니 다.
if __name__ == "__main__":
parser = OptionParser()
group = OptionGroup(parser, "FTP download tool", "Download build from ftp server")
group.add_option("--server", type="string", help="FTP server's IP address")
group.add_option("--username", type="string", help="User name")
group.add_option("--password", type="string", help="User's password")
group.add_option("--buildpath", type="string", help="Build path in the ftp server")
group.add_option("--buildname", type="string", help="Build name to be downloaded")
parser.add_option_group(group)
(options, args) = parser.parse_args()
local_dir = "/exports/images"
lock_file = "/var/tmp/flock.txt"
flock = Lock(lock_file)
flock.lock()
if os.path.isfile(os.path.join(local_dir, options.buildname)):
log.info("build exists, nothing needs to be done")
log.info("Download completed")
flock.unlock()
exit(0)
log.info("start to download build " + options.buildname)
t = paramiko.Transport((options.server, 22))
t.connect(username=options.username, password=options.password)
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(os.path.join(options.buildpath, options.buildname),
os.path.join(local_dir, options.buildname))
sftp.close()
t.close()
log.info("Download completed")
flock.unlock()
파 이 썬 관련 내용 에 관심 이 있 는 독자 들 은 본 사이트 의 주 제 를 볼 수 있 습 니 다.,,,, 및《 Python 파일 과 디 렉 터 리 조작 기법 집합 》
본 논문 에서 말 한 것 이 여러분 의 Python 프로 그래 밍 에 도움 이 되 기 를 바 랍 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.