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

运行效果

231906_6laH_1425762.png

代码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

运行效果

232242_9Iep_1425762.png

END

转载于:https://my.oschina.net/Tsybius2014/blog/318721

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值