2015-10-24 66 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()的认识;) –

相关问题