如果我有一个管道来运行某些命令,则管道命令需要进行一些清理,但是,如果启动管道的进程有错误,则管道命令不会清理。在这种情况下,管道命令是否获得 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);
}