我刚刚接触 Linux 中的管道 I/O 功能。 制作了 2 个 c 文件,第一个发送数据:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int i = 0;
for(;;)
{
printf("\nSent number: %d",i);
i++;
sleep(1);
fflush(stdout);
}
return 0;
}
第二个文件接收打印的数字并显示它:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main(int argc, char* argv[])
{
int x;
for(;;)
{
scanf("%d",&x);
printf("Received number: %d\n",x);
sleep(1);
fflush(stdout);
}
return 0;
}
最后,我尝试将数据从第一个文件重定向到第二个文件:
./send_test.out | ./rcv_test.out
终端重复打印:“收到的号码:0”,我做错了什么? 另外,我如何才能同时运行两个程序的终端窗口,同时将输出从发送方定向到接收方?
提前致谢
最佳答案
您没有以接收者可以理解的格式“发送”号码。
尝试从发件人的格式字符串中删除除 %d
之外的所有文本。
此外,在依赖 scanf()
之前,您应该检查它的返回值。
关于c - 使用 2 个 c 文件的 Linux 命令行重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23055369/