1. 程式人生 > >Linux程序間通訊——pipe應用例項

Linux程序間通訊——pipe應用例項

    管道(pipe):管道可用於具有親緣關係的程序間的通訊,是一種半雙工的方式,資料只能單向流動,允許一個程序和另一個與它有共同祖先的程序之間進行通訊。

PIPE模組程式一

下面模組程式碼是在主函式中創將一個程序,在子程序中往管道中寫資料,在父程序中讀取資料,也就是一對一的讀寫操作。

/*============================================================================= 
#     FileName: pipe1.c
#         Desc: an example of pipe communication application
#       Author: Licaibiao 
#      Version:  
#   LastChange: 2017-01-09  
#      History: 
 
=============================================================================*/
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(int argc, char *argv[])
{    
	pid_t pid;
	int fd[2];
	int read_count = 0;
	int i;
	char read_buffer[10] = {0};
	char write_buffer[10] = {0};

	/*create pipe*/
	if (pipe(fd) < 0)
	{
		printf("Create pipe failed\n");
		return -1;
	}

	/*create process*/
	if ((pid = fork()) < 0)
	{
		printf("Fork failed\n");
		return -1;
	}

	/* child */
	if (pid == 0)
	{
		printf("[child]Close read endpoint...\n");
		/* close read */
		close(fd[0]);   		
		for(i=0;i<10;i++)
		{
			write_buffer[i]=i;	
		}
		write(fd[1],write_buffer,i);

	}
	 /*father*/
	else
	{
		printf("[parent]Close write endpoint...\n");
		/* close write */
		close(fd[1]);   
		read_count = read(fd[0], read_buffer, 10);
		printf("father process read data\n");
		for(i=0; i<read_count; i++)
		{
			printf("read_buffer[%d] = %d\n",i,read_buffer[i]);
		}
	}
}
程式執行結果:
[email protected]:/home/share/pipe# gcc pipe1.c -o test
[email protected]:/home/share/pipe# ./test 
[parent]Close write endpoint...
[child]Close read endpoint...
father process read data
read_buffer[0] = 0
read_buffer[1] = 1
read_buffer[2] = 2
read_buffer[3] = 3
read_buffer[4] = 4
read_buffer[5] = 5
read_buffer[6] = 6
read_buffer[7] = 7
read_buffer[8] = 8
read_buffer[9] = 9
PIPE模組程式二

    下面的程式是在主程序中建立了三個子程序,在子程序中寫入資料,在父程序中讀出資料,這裡使用的是多程序寫入,因此需要對檔案程序加鎖,這裡使用的了lockf函式。

/*============================================================================= 
#     FileName: pipe2.c
#         Desc: three process write piep and father process read data
#       Author: Licaibiao 
#      Version:  
#   LastChange: 2017-01-09  
#      History: 
 
=============================================================================*/
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int main(void)
{
    int fd[2];
    int i;
    int pid[3]={1,1,1};
    char outpipe[100],inpipe[100];

    pipe(fd);
 
    /* create three process */
    for(i=0;i<3;i++)
    {
        pid[i]=fork( );
        if(pid[i]==0)
        break;
    }
    if(pid[0]==0)
    {
        lockf(fd[1],F_LOCK,0);
        sprintf(outpipe,"child 1 process is sending message!");   
        write(fd[1],outpipe,50);    
        sleep(5);                
        lockf(fd[1],F_ULOCK,0);
        exit(0);
    }
    if(pid[1]==0)
    {  
        lockf(fd[1],F_LOCK,0);
        sprintf(outpipe,"child 2 process is sending message!");
        write(fd[1],outpipe,50);
        sleep(5);
        lockf(fd[1],F_ULOCK,0);
        exit(0);
    }
   
    if(pid[2]==0)
    {  
        lockf(fd[1],F_LOCK,0);
        sprintf(outpipe,"child 3 process is sending message!");
        write(fd[1],outpipe,50);
        sleep(5);
        lockf(fd[1],F_ULOCK,0);
        exit(0);
    }
    wait(0);
    read(fd[0],inpipe,50);  
    printf("%s\n",inpipe);
 
    read(fd[0],inpipe,50);
    printf("%s\n",inpipe);
 
    read(fd[0],inpipe,50);
    printf("%s\n",inpipe);
    return 0;
}
這裡建立了三個程序,程序執行的順序是不確定的,當pipe被鎖定的時候,其他的請求操作這個檔案的程序將被阻塞,直到pipe被解除鎖定之後,其他的程序之間進行競爭決定誰先誰後執行。多次執行結果下:
[email protected]:/home/share/pipe# gcc pipe2.c -o test
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 2 process is sending message!
child 3 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 3 process is sending message!
child 2 process is sending message!
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
child 1 process is sending message!
child 3 process is sending message!
child 2 process is sending message!
[email protected]:/home/share/pipe# 
如果要固定執行先後順序,可以把子程序一個一個的分開來建立,每建立一個子程序就請求操作pipe,最後在父進中讀取就可以了。

PIPE模組程式三

下面的程式是兩個程序寫入,兩個程序讀取,在pipe中寫入的資料,其他的程序再讀取的時候,將讀取不到資料。程式程式碼如下:

/*============================================================================= 
#     FileName: pipe3.c
#         Desc: two process write into pipe and two process read from pipe
#       Author: Licaibiao 
#      Version:  
#   LastChange: 2017-01-09  
#      History: 
=============================================================================*/
#include <sys/wait.h>
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#include <stdio.h>
int main(void)
{
    int fd[2], i;
	int pid[3] = {1,1,1};
    char outpipe[100],inpipe[100];
    pipe(fd);
    for(i=0;i<3;i++)
{
        pid[i]=fork( );
        if(pid[i]==0)
            break;
    }
    if(pid[0]==0)
    {
        lockf(fd[1],F_LOCK,0);
        sprintf(outpipe,"child 1 process is sending message!");   
        write(fd[1],outpipe,50);    
        sleep(5);                
        lockf(fd[1],F_ULOCK,0);
        exit(0);
    }
    if(pid[1]==0)
    {  
        lockf(fd[1],F_LOCK,0);
        sprintf(outpipe,"child 2 process is sending message!");
        write(fd[1],outpipe,50);
        sleep(5);
        lockf(fd[1],F_ULOCK,0);
        exit(0);
    }
   
    if(pid[2]==0)
    {  
        lockf(fd[0],F_LOCK,0);
        read(fd[0],inpipe,50);
        printf("Child 3 read:\n%s\n",inpipe);
        lockf(fd[0],F_ULOCK,0);
        exit(0);
    }
    wait(0);
    read(fd[0],inpipe,50);  
    printf("Parent read:\n%s\n",inpipe);
    exit(0);
}

執行結果如下:
[email protected]:/home/share/pipe# vim pipe3.c 
[email protected]:/home/share/pipe# gcc pipe3.c -o test 
[email protected]:/home/share/pipe# ./test 
Child 3 read:
child 2 process is sending message!
Parent read:
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
Child 3 read:
child 2 process is sending message!
Parent read:
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
Child 3 read:
child 2 process is sending message!
Parent read:
child 1 process is sending message!
[email protected]:/home/share/pipe# ./test 
Child 3 read:
child 2 process is sending message!
Parent read:
child 1 process is sending message!


相關推薦

Linux程序通訊——pipe應用例項

    管道(pipe):管道可用於具有親緣關係的程序間的通訊,是一種半雙工的方式,資料只能單向流動,允許一個程序和另一個與它有共同祖先的程序之間進行通訊。 PIPE模組程式一 下面模組程式碼是在主函式中創將一個程序,在子程序中往管道中寫資料,在父程序中讀取資料,也就是一對

Linux程序通訊——訊息佇列應用例項

    訊息佇列是訊息的連結表,包括Posix訊息佇列system V訊息佇列。有足夠許可權的程序可以向佇列中新增訊息,被賦予讀許可權的程序則可以讀走佇列中的訊息。訊息佇列克服了訊號承載資訊量少,管道只能承載無格式位元組流以及緩衝區大小受限等缺點。下面是兩個測試模組接收模組m

c/c++ linux 程序通訊系列3,使用socketpair,pipe

linux 程序間通訊系列3,使用socketpair,pipe 1,使用socketpair,實現程序間通訊,是雙向的。 2,使用pipe,實現程序間通訊 使用pipe關鍵點:fd[0]只能用於接收,fd[1]只能用於傳送,是單向的。 3,使用pipe,用標準輸入往裡寫。 疑問:在

Linux程序通訊pipe

1、管道(PIPE)        從概念上說,管道是兩個程序之間的一個connection,因此一個程序的標準輸出就變成了另一個程序的標準輸入。在Unix作業系統中,管道用於程序間通訊(inter-process communication). (1

Linux 程序通訊方式 pipe()函式

Linux 程序間通訊方式有以下幾種: 1-》管道(pipe)和有名管道(fifo). 2-》訊息佇列 3-》共享記憶體 4-》訊號量 5-》訊號(signal) 6-》套接字(sicket) 在這裡我們看一下第一種====管道(pipe)。有名管道(fifo)見其它文章。

linux 程序通訊三 訊息佇列以及例項

程式碼來自:嵌入式linux應用開發標準教程 訊息可以理解為寫信給某個人,這裡在應用中是告訴系統寫信人和寫信的內容就可以了, 別人會來看發信人是誰,如果不是自己想要的就放棄讀信或者只要有訊息自己就讀取訊息 訊息佇列就是按佇列的方式處理很多訊息,先發的最先被讀 訊息佇列:

Linux程序通訊分類 以及 pipe的原理實現

一個大型的應用系統,往往需要眾多程序協作,程序(Linux程序概念見附1)間通訊的重要性顯而易見。本系列文章闡述了Linux環境下的幾種主要程序間通訊手段,並針對每個通訊手段關鍵技術環節給出詳細例項。為達到闡明問題的目的,本文還對某些通訊手段的內部實現機制進行了分析。

Linux程序通訊(IPC)方式總結

程序間通訊概述 程序通訊的目的 資料傳輸  一個程序需要將它的資料傳送給另一個程序,傳送的資料量在一個位元組到幾M位元組之間 共享資料  多個程序想要操作共享資料,一個程序對共享資料 通知事件 一個程序需要向另一個或一組程序傳送訊息,通知它(它們)

c/c++ linux 程序通訊系列7,使用pthread mutex

linux 程序間通訊系列7,使用pthread mutex #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/shm.h> #include <pthr

c/c++ linux 程序通訊系列4,使用共享記憶體

linux 程序間通訊系列4,使用共享記憶體 1,建立共享記憶體,用到的函式shmget, shmat, shmdt 函式名 功能描述 shmget 建立共享記憶體,返回pic key

linux 程序通訊之FIFO

1.概述 FIFO與管道幾乎類似,所以FIFO也是一個位元組流,從FIFO讀取的順序也是與被寫入FIFO的順序一致,容量是也有限的,也是可以確保寫入不超過PIPE_BUF位元組的操作是原子的,FIFO的本質也是一個管道,但傳遞方向是可以雙向的,它們兩者之間的最大差別在於FIFO在檔案系統中擁有一個名稱,並且

c/c++ linux 程序通訊系列2,使用UNIX_SOCKET

linux 程序間通訊系列2,使用UNIX_SOCKET 1,使用stream,實現程序間通訊 2,使用DGRAM,實現程序間通訊 關鍵點:使用一個臨時的檔案,進行資訊的互傳。 s_un.sun_family = AF_UNIX; strcpy(s_un.sun_path, "

c/c++ linux 程序通訊系列1,使用signal,kill

linux 程序間通訊系列1,使用signal,kill 訊號基本概念:  軟中斷訊號(signal,又簡稱為訊號)用來通知程序發生了非同步事件。程序之間可以互相通過系統呼叫kill傳送軟中斷訊號。核心也可以因為內部事件而給程序傳送訊號,通知程序發生了某個事件。注意,訊號只是用來通知某程序發生了什

Linux程序通訊IPC的幾種方式簡介

Linux程序通訊的源頭       linux下的程序通訊手段基本上是從Unix平臺上的程序通訊手段繼承而來的。而對Unix發展做出重大貢獻的兩大主力AT&T(原為American Telephone & Tele

Linux程序通訊總結

  目錄 訊號 管道 命名管道 System V IPC 組成 識別符號 ftok函式 結構定義 特點 訊息佇列 訊號量 共享記憶體 套接字 Linux下的程序間通訊(Interprocess Communication,

AIDL 安卓程序通訊/跨應用通訊

前言 最近出去面試找工作,被人問到AIDL,我就回答這個東西我用過,也大概理解,Android的程序間通訊語言嘛,人家不置可否,那我能咋著呢,畢竟沒深入研究過,也沒辦法,咱只能回來奮發圖強了 寫在前面 我以前就看過的一個部落格,裡面原理程式碼什麼都有,寫的水平肯定比我高 A

linux 程序通訊方式

1 無名管道通訊 無名管道( pipe ):管道是一種半雙工的通訊方式,資料只能單向流動,而且只能在具有親緣關係的程序間使用。程序的親緣關係通常是指父子程序關係。 2 高階管道通訊 高階管道(popen):將另一個程式當做一個新的程序在當前程式程序中啟動,則它算是當前程式的子程序

Linux 程序通訊的一種實現方式

程序間通訊的方式一般有三種:管道(普通管道、流管道和命名管道)、系統IPC(訊息佇列、訊號和共享儲存)、套接字(Socket) 本部落格以之前所做的智慧車專案為例,簡單介紹下共享儲存的一種實現過程。簡單說來,程序1將資料寫入到一個公共檔案input.txt中,程序2對其進行

Linux 程序通訊(四)訊號量

1 訊號量概述 訊號量和其他IPC不同,並沒有在程序之間傳送資料,訊號量用於多程序在存取共享資源時的同步控制就像交通路口的紅路燈一樣,當訊號量大於0,表示綠燈允許通過,當訊號量等於0,表示紅燈,必須停下來等待綠燈才能通過。 程序間的互斥關係與同步關係存在的根源在於臨界資

Linux 程序通訊(五)IPC的特性

1.識別符號和鍵 每個核心中的IPC結構(訊息佇列、訊號量或共享儲存段)都用一個非負整數的識別符號 (identifier)加以引用。 例如,要向一個訊息佇列傳送訊息或者從一個訊息佇列取訊息,只需要知道其佇列識別符號。 當一個IPC結構被建立,然後又被刪除時,與這種結構