1
Imagickが作成するまでimg.jpgファイルをロックすることはできますか?Imagick writeImage()の実行中にファイルをロックする
$image->writeImage('img.jpg')
Imagickが作成するまでimg.jpgファイルをロックすることはできますか?Imagick writeImage()の実行中にファイルをロックする
$image->writeImage('img.jpg')
説明している問題が実際に問題として存在するかどうかは完全にはわかりません。他にはそれを報告したことはない。
ただし、問題があっても、ここでファイルロックを使用したくない場合は、別の問題を解決するためです。
代わりに、あなたが使いたいのはアトミック操作です。これは、コンピュータによって「即時」に行われます。
$created = false;
for ($i=0; $i<5 && $created == false; $i++) {
// Create a temp name
$tmpName = "temp".rand(10000000, 99999999).".jpg";
// Open it. The x+ means 'do not create if file already exists'.
$fileHandle = @fopen($tmpName, 'x+');
if ($fileHandle === false) {
// The file with $tmpName already exists, or we otherwise failed
// to create the file, loop again.
continue;
}
// We don't actually want the file-handle, we just wanted to make sure
// we had a uniquely named file ending with .jpg so just close it again.
// You could also use tempnam() if you don't care about the file extension.
fclose($fileHandle);
// Writes the image data to the temp file name.
$image->writeImage($tmpName);
rename($tmpName, 'img.jpg');
$created = true;
}
if ($created === false) {
throw new FailedToGenerateImageException("blah blah");
}
は、そこに何のロックもありません....しかし、それが書き込まれている間、任意のプロセスがimg.jpgからデータを読み取ることができません。名前の変更中にimg.jpgを持つ他のプロセスが存在する場合、ファイルの古いバージョンに対するファイルハンドルは引き続き存在し、それらを閉じて再度開くまで古いファイルを読み込み続けます。
あなたはこれをやりたい理由を言うことができますか?理由を想像してみることもできますが、ユースケースが明確であればあなたの質問に答えるのが簡単になります。 – Danack
@Danackユーザーがこのファイルを既に作成しているが作成されていないときに取得しようとすると、ユーザーがファイルを破損する –
これは実際に起こったことがありますか? ImageMagickはアトミックファイル操作を使用する必要があります... – Danack