進程間通信(IPC)作用
1.數據傳輸
2.共享資源
3.通知事件
4.進程控制
IPC的方式 6種
1.管道(pipe)和有名管道(FIFO)
2.信號(signal)
3.消息隊列
4.共享內存
5.信號量
6.套接字
管道
一進程寫入管道尾部,另一進程從管道頭讀出
讀空管道,進程被阻塞
寫滿管道,進程被阻塞
無名管道 多用于父子進程間的通信
filedis文件描述符
filedis[0]用于讀管道
filedis[1]用于寫管道
通常 先創建一個管道, 再通過fork創建一個子進程 ,子進程會繼承父進程所創建的管道
有名管道
pathname:FIFO的路徑
讀寫管道時: 非阻塞標志O_NONBLOCK,非阻塞時,出錯立即返回,errno是ENXIO
刪除管道
讀有名管道
寫有名管道
1.數據傳輸
2.共享資源
3.通知事件
4.進程控制
IPC的方式 6種
1.管道(pipe)和有名管道(FIFO)
2.信號(signal)
3.消息隊列
4.共享內存
5.信號量
6.套接字
管道
一進程寫入管道尾部,另一進程從管道頭讀出
讀空管道,進程被阻塞
寫滿管道,進程被阻塞
無名管道 多用于父子進程間的通信
int pipe(int filedis[2])//創建無名管道
filedis文件描述符
filedis[0]用于讀管道
filedis[1]用于寫管道
//管道的創建和關閉
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
int pipe)fd[2];
//創建pipe
if(pipe(pipe_fd)<0){
printf("pipe create error\n");
return -1;
}else{
printf("pipe create success\n"):
}
//關閉pipe
close(pipe_fd[0]);
colse(pipe_fd[1]);
}
通常 先創建一個管道, 再通過fork創建一個子進程 ,子進程會繼承父進程所創建的管道
有名管道
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode)
pathname:FIFO的路徑
讀寫管道時: 非阻塞標志O_NONBLOCK,非阻塞時,出錯立即返回,errno是ENXIO
刪除管道
unlink(const char *pathname)
讀有名管道
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO "/tmp/myfifo"
main(int argc,char** argv)
{
char buf_r[100];
int fd;
int nread;
/* 創建管道 */
if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))
printf("cannot create fifoserver\n");
printf("Preparing for reading bytes...\n");
memset(buf_r,0,sizeof(buf_r));
/* 打開管道 */
fd=open(FIFO,O_RDONLY|O_NONBLOCK,0);
if(fd==-1)
{
perror("open");
exit(1);
}
while(1)
{
memset(buf_r,0,sizeof(buf_r));
if((nread=read(fd,buf_r,100))==-1)
{
if(errno==EAGAIN)
printf("no data yet\n");
}
printf("read %s from FIFO\n",buf_r);
sleep(1);
}
pause(); /*暫停,等待信號*/
unlink(FIFO); //刪除文件
}
寫有名管道
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FIFO_SERVER "/tmp/myfifo"
main(int argc,char** argv)
{
int fd;
char w_buf[100];
int nwrite;
/*打開管道*/
fd=open(FIFO_SERVER,O_WRONLY|O_NONBLOCK,0);
if(argc==1)
{
printf("Please send something\n");
exit(-1);
}
strcpy(w_buf,argv[1]);
/* 向管道寫入數據 */
if((nwrite=write(fd,w_buf,100))==-1)
{
if(errno==EAGAIN)
printf("The FIFO has not been read yet.Please try later\n");
}
else
printf("write %s to the FIFO\n",w_buf);
}
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

