我使用以下程序写入 fifo:
#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;
}
如果我启动这个程序,启动另一个 shell 并在那里输入
cat < fifo1
我可以看到程序向管道写入了一些内容,并且我可以在读取 shell 中看到输出。如果我用 CTRL^C 停止 cat 命令,FIFO Writer 也会终止,没有错误消息。这是什么原因?为什么没有抛出错误?
奇怪的是,如果我用 Eclipse CDT 启动上面的代码并用 CTRL^C 关闭读取 shell,程序会继续打印“错误:3”。
期待你的想法,海因里希