當前位置:首頁 » 編程語言 » c語言linux管道
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

c語言linux管道

發布時間: 2023-02-11 15:57:10

❶ linux下的C語言開發(管道通信)

姓名:馮成 學號:19020100164 學院:丁香二號書院

轉自:https://feixiaoxing.blog.csdn.net/article/details/7229483

【嵌牛導讀】本文將介紹linux下的C語言開發中的管道通信

【嵌牛鼻子】linux C語言 管道通信

【嵌牛提問】linux下的C語言開發中的管道通信是什麼?

Linux系統本身為進程間通信提供了很多的方式,比如說管道、共享內存、socket通信等。管道的使用十分簡單,在創建了匿名管道之後,我們只需要從一個管道發送數據,再從另外一個管道接受數據即可。

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <string.h>

int pipe_default[2]; 

int main()

{

    pid_t pid;

    char buffer[32];

    memset(buffer, 0, 32);

    if(pipe(pipe_default) < 0)

    {

        printf("Failed to create pipe!\n");

        return 0;

    }

    if(0 == (pid = fork()))

    {

        close(pipe_default[1]);

        sleep(5);

        if(read(pipe_default[0], buffer, 32) > 0)

        {

            printf("Receive data from server, %s!\n", buffer);

        }

        close(pipe_default[0]);

    }

    else

    {

        close(pipe_default[0]);

        if(-1 != write(pipe_default[1], "hello", strlen("hello")))

        {

            printf("Send data to client, hello!\n");

        }

        close(pipe_default[1]);

        waitpid(pid, NULL, 0);

    }

    return 1;

}

    下面我們就可以開始編譯運行了,老規矩分成兩步驟進行:(1)輸入gcc pipe.c -o pipe;(2)然後輸入./pipe,過一會兒你就可以看到下面的列印了。

[test@localhost pipe]$ ./pipe

Send data to client, hello!

Receive data from server, hello!

❷ linux下C語言編程,管道,p,fork,疑問的是,為什麼連用那麼多close必須要close 代碼如下

文件描述符0,1,2分別表示標准輸入標准輸出,標准錯誤輸出, 所以在子進程里close(1)是關閉了標准輸出, 然後用p(fda[1]);此時未用的最小文件描述符就是1(被關閉);這里關閉fda[0]就是為了說明在子進程是管道的寫端(fda[0],不關閉是可以的為了保險起見關閉).然後子進程退出會調用系統程序ls,於是當前的文件目錄就被發送到管道中.父進程同理, 就是將標准輸出作為管道的讀端,它讀到的是子進程ls後的內容,對文件計數,