Linux下的C程序,通过最简单的管道(‘|‘)实现两个程序间的数据传递
本文中使用的管道,是Linux中把前一个程序的输出放到后一个程序的输入的‘|‘符号,并不是自己实现的管道
代码1:程序a.c输出“HelloWorld”,并由b.c通过管道接住输出
a.c代码
#include <stdio.h> void main() { printf("Hello World! :-P\n"); }
b.c代码
#include <stdio.h> void main() { char input[100]; char ch; int i = 0; while(ch = getchar()) { if (ch != ‘\n‘) { input[i++] = ch; } else { input[i] = ‘\0‘; break; } } printf(":-) %s\n", input); }
编译和运行,输入命令:
gcc a.c -o a gcc b.c -o b ./a | ./b
运行效果
代码2:程序a.c以参数的形式输入颜色,传给b.c,输出指定颜色的"Hello World!"
a.c代码
#include <stdio.h> #include <stdlib.h> void main(int argc, char *argv[]) { //输出main函数接收到的参数 int i; for (i = 1; i < argc; i++) { printf("%s\n", argv[i]); } printf("end\n"); exit(EXIT_SUCCESS); }
b.c代码
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { char s[20]; while (1) { scanf("%s", s); if (strcmp(s, "black") == 0) { printf("\e[30;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "red") == 0) { printf("\e[31;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "green") == 0) { printf("\e[32;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "yellow") == 0) { printf("\e[33;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "blue") == 0) { printf("\e[34;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "purple") == 0) { printf("\e[35;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "darkgreen") == 0) { printf("\e[36;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "white") == 0) { printf("\e[37;40;1m%s\e[37;40;0m\n", "Hello World!"); } else if (strcmp(s, "end") != 0) { printf("Hello World! (UNKNOWN COLOR)\n"); } else { printf("END!\n"); break; } } exit(EXIT_SUCCESS); }
编译和运行,输入命令:
gcc a.c -o a gcc b.c -o b ./a 参数 | ./b
运行效果
END
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。