雷火电竞-中国电竞赛事及体育赛事平台

歡迎來(lái)到入門(mén)教程網(wǎng)!

C語(yǔ)言

當(dāng)前位置:主頁(yè) > 軟件編程 > C語(yǔ)言 >

linux 匿名管道實(shí)例詳解

來(lái)源:本站原創(chuàng)|時(shí)間:2020-01-10|欄目:C語(yǔ)言|點(diǎn)擊:

linux中進(jìn)程的一種通信方式——匿名管道

pipe函數(shù)建立管道

調(diào)用pipe函數(shù)時(shí)在內(nèi)核中開(kāi)辟一塊緩沖區(qū)(稱為管道)用于通信,它有一個(gè)讀端一個(gè)寫(xiě)端,然后通過(guò)_pipe參數(shù)傳出給用戶程序兩個(gè)文件描述符,_pipe[0]指向管道的讀端,_pipe[1]指向管道的寫(xiě)端。所以管道在用戶程序看起來(lái)就像一個(gè)打開(kāi)的文件,通過(guò)read(_pipe[0]);或者write(_pipe[1]);向這個(gè)文件讀寫(xiě)數(shù)據(jù)其實(shí)是在讀寫(xiě)內(nèi)核緩沖區(qū)。pipe函數(shù)調(diào)用成功返回0,調(diào)用失敗返回-1。

1父進(jìn)程調(diào)用pipe開(kāi)辟管道,得到兩個(gè)文件描述符指向管道的兩端。

2. 父進(jìn)程調(diào)用fork創(chuàng)建⼦進(jìn)程,那么子進(jìn)程也有兩個(gè)文件描述符指向同一管道。

3. 父進(jìn)程關(guān)閉管道讀端,子進(jìn)程關(guān)閉管道寫(xiě)端。父進(jìn)程可以往管道里寫(xiě),子進(jìn)程可以從管道⾥讀,管道是用環(huán)形隊(duì)列實(shí)現(xiàn)的,數(shù)據(jù)從寫(xiě)端流入從讀端流出,這樣就實(shí)現(xiàn)了進(jìn)程間通信

匿名管道間的通信是單向的,并且是、只能是具有血緣關(guān)系的進(jìn)程間通信



#include<stdio.h> 
#include<unistd.h> 
#include<string.h> 
#include<stdlib.h> 
 
int main() 
{ 
  int _pipe[2]; 
  int ret = pipe(_pipe); 
  if (ret < 0) 
  { 
    perror("pipe"); 
    return 1; 
  } 
  pid_t id = fork (); 
  if (id<0) 
  { 
    perror("fork"); 
    return 2; 
  } 
  else if (id == 0) 
  { 
    // child 
    int count =5; 
    close (_pipe[0]); 
    char* msg = "hello bit"; 
    while (count --) 
    { 
      write(_pipe[1],msg,strlen(msg)); 
      sleep(1); 
    } 
    close (_pipe[1]); 
    exit(123); 
  } 
  else  
  { 
    // Father 
    close(_pipe[1]); 
    char buf[128]; 
    while(1) 
    { 
      int count =5; 
      ssize_t s = read ( _pipe[0],buf,sizeof(buf)-1); 
      if (s<0) 
      { 
        perror("read"); 
      } 
      else if(s==0) 
      { 
        printf("write is close\n"); 
        return 2; 
      } 
      else 
      { 
        buf[s] ='\0'; 
        printf ("child >> father: %s\n",buf); 
      } 
      count --; 
      if (count == 0) 
      { 
        close (_pipe[0]); 
        break; 
      } 
    } 
     
    int status = 0; 
    pid_t _wait = waitpid (id, &status,0); 
    if (_wait > 0) 
    { 
      printf("exit code is %d, signal is %d\n", 
          WIFEXITED(status), status & 0xff); 
    } 
 
    } 
     
  return 0; 
} 

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

上一篇:面試題快慢鏈表和快慢指針

欄    目:C語(yǔ)言

下一篇:C程序中唯一序列號(hào)的生成實(shí)例詳解

本文標(biāo)題:linux 匿名管道實(shí)例詳解

本文地址:http://www.jygsgssxh.com/a1/Cyuyan/1439.html

網(wǎng)頁(yè)制作CMS教程網(wǎng)絡(luò)編程軟件編程腳本語(yǔ)言數(shù)據(jù)庫(kù)服務(wù)器

如果侵犯了您的權(quán)利,請(qǐng)與我們聯(lián)系,我們將在24小時(shí)內(nèi)進(jìn)行處理、任何非本站因素導(dǎo)致的法律后果,本站均不負(fù)任何責(zé)任。

聯(lián)系QQ:835971066 | 郵箱:835971066#qq.com(#換成@)

Copyright © 2002-2020 腳本教程網(wǎng) 版權(quán)所有