1-》管道(pipe)和有名管道(fifo).
2-》消息隊列
3-》共享內存
4-》信號量
5-》信號(signal)
6-》套接字(sicket)
在Linux系統中,管道通信可以通過使用系統調用來實現。
使用格式爲:
表頭文件 #include<unistd.h>
定義函數 int pipe(int filedes[2]);
函數說明
pipe()會建立管道,並將文件描述詞由參數 filedes 數組返回。
filedes[0]爲管道里的讀取端,所以pipe用read調用的
filedes[1]則爲管道的寫入端。
返回值: 若成功則返回零,否則返回-1,錯誤原因存於 errno 中。
錯誤代碼:
EMFILE 進程已用完文件描述詞最大量
ENFILE 系統已無文件描述詞可用。
EFAULT 參數 filedes 數組地址不合法。
但值得我們注意的是:管道它有自身的特點。
(1)管道通信是單向的,並且遵守先進先出的原則,即先寫入的數據先讀出。
(2)管道是一個無結構,無固定大小的字節流。
(3) 管道把一個進程的標準輸出和另一個進程的標準輸入連接在一起。數據讀出後就意味着從管道中移走了,消失了。其它的進程都不能
再讀到這些數據。就像我們平常見到的管子水流走了就沒有了。 這點很重要!!
(4) pipe這種管道用於兩個有親緣關係的進程之間。eg:父子進程......
#include <unistd.h>
#include <stdio.h>
int main( void )
{
int filedes[2];
char buf[80];
pid_t pid;
pipe( filedes );
if ( (pid=fork()) > 0 )
{
printf( "This is in the father process,here write a string to the pipe.\n" );
char s[] = "Hello world , this is write by pipe.\n";
write( filedes[1], s, sizeof(s) );
close( filedes[0] );
close( filedes[1] );
}
else
{
printf( "This is in the child process,here read a string from the pipe.\n" );
read( filedes[0], buf, sizeof(buf) );
printf( "%s\n", buf );
close( filedes[0] );
close( filedes[1] );
}
waitpid( pid, NULL, 0 );
return 0;
}