2015-10-24 67 views
1

我已經做了兩個簡單的程序:Linux系統:一個程序的管道輸出到另一個

out.c

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
    int x; 
    srand((unsigned int)time(NULL)); 
    for(;;) 
    { 
     x = rand(); 
     printf("%d\n", x % 100); 
     sleep(1); 
    } 
    return 0; 
} 

in.c

​​

我運行它像./out | ./in,但我沒有得到任何印刷。什麼是以管道輸入的方式運行的正確方法

+0

這是一個鏈接,我發現,http://unix.stackexchange.com/questions/40277/is-there-a-way-to-pipe-the-output-of-one-program-into - 其他程序,但我不認爲這在這種情況下是相關的。 –

+0

http://stackoverflow.com/questions/2784500/how-to-send-a-simple-string-between-two-programs-using-pipes – Jrican

回答

1

此問題可以通過在out.c程序中刷新stdout來解決。你需要這樣做,因爲如果stdout不是tty,它不會自動刷新,這取決於你的操作系統。

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
    int x; 
    srand((unsigned int)time(NULL)); 
    for(;;) 
    { 
     x = rand(); 
     printf("%d\n", x % 100); 
     fflush(stdout); // <-- this line 
     sleep(1); 
    } 
    return 0; 
} 
+0

哦,太棒了!實際上,這確實說明了我對fflush()的認識;) –

相關問題