コマンドを実行するためのパイプがある場合、パイプされたコマンドはクリーンアップを行う必要がありますが、パイプを開始したプロセスにエラーがある場合、パイプされたコマンドはクリーンアップされません。この場合、パイプされたコマンドは SIGPIPE を取得していますか? cleanupPipe デストラクタが常に実行されるようにするにはどうすればよいですか? errorOccurred 例外がスローされると、cleanupPipe デストラクタが実行されていないことがわかります。例外をスローするように SIGPIPE ハンドラーを設定しているので、結果が SIGPIPE の場合、SIGPIPE の結果として例外がスローされ、スタックが巻き戻されたときに、デストラクタが実行されることを期待します。
void
testCase() {
class cleanup {
public:
cleanup(FILE *pipe)
: _pipe(pipe) {
}
~cleanup() {
::pclose(_pipe);
}
private:
FILE *_pipe;
};
string cmd("runMyCommandImplementationHere argsHere");
FILE *pipePtr = ::popen(cmd, "w");
cleanup cleanUpPipe(pipePtr);
// Normally, write data to pipe until process in pipe gets all the data it
// needs and exits gracefully.
for (;;) {
if (someErrorOccured()) {
// When this error occurs, we want to ensure cleanupPipe is run in piped
// process.
throw errorOccurred(status);
}
if (finishedWritingData()) {
break;
}
writeSomeDataToPipe(pipePtr);
}
}
void
myCommandImplementationHere() {
class cleaupPipe {
public:
cleanupPipe(const string &filename)
: _filename(filename) {
}
~cleanupPipe() {
::unlink(_filename.c_str());
}
private:
string _filename;
};
string file("/tmp/fileToCleanUp");
cleanupPipe cleanup(file);
doSomeWorkOnFileWhileReadingPipeTillDone(file);
}