发布时间:2024-04-03 13:01
本文中使用的管道,是Linux中把前一个程序的输出放到后一个程序的输入的\'|\'符号,并不是自己实现的管道
代码1:程序a.c输出“HelloWorld”,并由b.c通过管道接住输出
a.c代码
#include
void main()
{
printf(\"Hello World! :-P\\n\");
}
b.c代码
#include
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
#include
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
#include
#include
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
转载于:https://my.oschina.net/Tsybius2014/blog/318721