Linux下的C程式,通過最簡單的管道(‘|‘)實現兩個程式間的資料傳遞

來源:互聯網
上載者:User

標籤:style   http   color   io   os   使用   ar   for   資料   

本文中使用的管道,是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 agcc 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 agcc b.c -o b./a 參數 | ./b

運行效果

END

Linux下的C程式,通過最簡單的管道(‘|‘)實現兩個程式間的資料傳遞

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.