2010-10-21 46 views
0

我用下面的程序寫入到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」。

期待你的想法, 海因裏希

+0

這是C++混合使用C – nategoose 2010-10-21 20:02:06

+0

這是C,混合C++的' cout' – 2010-10-21 20:07:22

+0

-1詢問C但向我們展示C++代碼。 – 2010-10-21 23:06:38

回答

3

如果你寫的時候管道的另一端已經關閉一個SIGPIPE將交付給你的程序的管道。沒有安裝的信號處理程序,這會立即終止您的程序。通常這是輸出,我不知道爲什麼不看這個。

如果你更喜歡檢查寫的錯誤代碼比得到一個SIGPIPE的代碼提示,你要忽略SIGPIPE:

#include <signal.h> 

signal(SIGPIPE, SIG_IGN); 
+0

從bash-3.1開始,bash默認不會報告SIGPIPE錯誤。 – 2010-10-21 20:39:23

+0

@亞歷山大,謝謝那麼一切都可能現在解釋 – 2010-10-21 20:42:36

+0

感謝您的答案,這是問題! – Erik 2010-10-22 15:17:42

相關問題