程序間通訊學習筆記一 管道通訊

2021-09-01 15:27:38 字數 2570 閱讀 6559

程序間通訊(ipc)

應用場景:

資料傳輸

資源共享

通知事件

程序控制

system v at&t system v

posix(portable operating system inte***ce)可移植作業系統介面

常用的程序間通訊的方式:

管道(pipe)和有名管道(fifo)

訊號(signal)

訊息佇列

共享記憶體

訊號量套接字(socket)

管道通訊

半雙工的,資料只能向乙個方向流動

只能用於父子程序間或兄弟程序間

先進先出,乙個程序在管道的尾部寫入資料,另乙個程序從管道的頭部讀出資料

無名管道 用於父子程序間的通訊

建立管道

int pipe(int filedis[2])

管道建立時,所建立的兩個檔案描述符

filedis[0] 管道的讀取端

filedis[1] 管道的寫入端

關閉管道

將兩個檔案描述符關閉

示例**如下:

#include

#include

#include

#include

int main()else

close(pipe_fd[0]);

close(pipe_fd[1]);

}管道的讀寫

選建立乙個管道,通過fork()函式建立乙個子程序,子程序會繼承父程序所建立的管道

示例**如下:

#include

#include

#include

#include

#include

int main()

/*建立子程序*/

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

close(pipe_fd[0]);

exit(0);

}else if(pid>0)

if(write(pipe_fd[1]," pipe",5)!=-1)

close(pipe_fd[1]);

sleep(3);

waitpid(pid,null,0);

exit(0);}}

執行結果如下:

[retacn@localhost tmp]$ gcc pipe_rw.c -o pipe_rw

[retacn@localhost tmp]$ ./pipe_rw

parent write1 hello!

parent write2 page!

10 number read form the pipe is hello pipe

有名管道 用於執行於同一系統中的任意兩個程序間的通訊

fifo,與無命管道的區別是不相關的程序也能交換資料

建立命名管道

#include

#include

int mkfifo(const char *pathname,mode_t mode)

pathname:fifo檔名

mode:屬性

當使用open開啟fifo檔案時,o_nonblock會產生以下影響

使用時,訪問要求無法滿足時不阻塞,立即返回,errno是enxio

不使用時,訪問要求無法滿足時程序將阻塞

示例**如下:

fifo_read.c

#include

#include

#include

#include

#include

#include

#include

#include

#define fifo "/home/retacn/tmp/myfifo"

main(int argc,char *argv)

printf("preparing for reading bytes...\n");

memset(buf_r,0,sizeof(buf_r));

/*開啟管道*/

fd=open(fifo,o_rdonly|o_nonblock,0);

if(fd==-1)

while(1)

}printf("read %s form fifo\n",buf_r);

sleep(1);

}/*暫停,等待訊號*/

pause();

}fifo_write.c

#include

#include

#include

#include

#include

#include

#include

#include

#define fifo_server "/home/retacn/tmp/myfifo"

main(int argc,char **argv)

strcpy(w_buf,argv[1]);

/*向管道寫入資料*/

if((nwrite=write(fd,w_buf,100))==-1)

}else

}

程序間通訊(一) 管道

一,用管道進行父子程序通訊 include include define maxline 120 define msginfo hurry up n int main void pid t pid if pipe fd 0 if pid fork 0 if pid 0 father write st...

Linux程序間通訊(一)管道

乙個程序在管道的尾部寫入資料,另乙個程序從管道的頭部讀出資料。管道包括無名管道和有名管道兩種,前者只能用於父程序和子程序間的通訊,後者可用於執行於同一系統中 的任意兩個程序間的通訊。管道通訊 特點 管道通訊是單向的,有固定的讀端和寫端。資料被程序從管道讀出後,在管道中該資料就不存在了。當程序去讀取空...

Linux IPC程序間通訊 一 管道

系列文章 linux ipc程序間通訊 一 管道 linux ipc程序間通訊 二 共享記憶體 linux ipc程序間通訊 三 訊號量 linux ipc程序間通訊 四 訊息佇列 linux程序間通訊 ipc 的乙個重要方法就是管道,在學習管道之前,要理解兩個概念 不論是無名管道還是有名管道,都屬...