我用下面的程序寫入到FIFO:的open()導致程序中止
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
using namespace std;
int main() {
unlink("fifo1");
if (mkfifo("fifo1", 0666) != 0) {
cout << "Error while creating fifo" << endl;
return 1;
}
else {
cout << "Fifo created" << endl;
}
int fd = open("fifo1", O_WRONLY);
if(fd == -1) {
cout << "Could not open file" << endl;
return 1;
}
else {
cout << "Fifo opened" << endl;
}
int i=0;
char* buffer = new char[20];
while(true) {
sprintf(buffer, "look: %i\n", i++);
int r = write(fd, buffer, strlen(buffer));
if(r == -1) {
cout << "Fifo Error:" << fd << endl;
}
else {
cout << "Wrote: " << i << "(" << r << "B)"<< endl;
}
sleep(1);
}
return 0;
}
如果我啓動該程序,啓動另一個外殼並鍵入有
cat < fifo1
我可以看到,該程序寫入管道的東西,我可以看到在閱讀shell中的輸出。如果我用CTRL^C停止cat命令,那麼FIFO編寫器也會終止,而不會出現錯誤信息。這是什麼原因?爲什麼不拋出錯誤?
奇怪的是,如果我用Eclipse CDT啓動上述代碼,並且閱讀shell用CTRL^C關閉,程序將繼續打印「Error:3」。
期待你的想法, 海因裏希
這是C++混合使用C – nategoose 2010-10-21 20:02:06
這是C,混合C++的' cout' – 2010-10-21 20:07:22
-1詢問C但向我們展示C++代碼。 – 2010-10-21 23:06:38