您的位置:首页 > 运维架构 > Linux

Linux工程实践学习笔记——基于主机系统的多客户即时通讯/聊天室 Day(3)

2012-11-06 09:45 856 查看
上一天 –进程控制 & 守护进程的创建

本讲内容:

IPC: Inter-Process Communication进程间通信

进程间通信机制

共享文件

信号

管道(pipe), 命名管道(FIFO), 消息队列,信号量,共享内存

套接字(socket)

无名管道

#include <unistd.h>

int pipe(int pipefd[2]);

参数说明

pipefd数组用来返回两个文件描述符,分别指向管道的两端

pipefd[0]: 管道的读端

pipefd[1]: 管道的写端

先进先出

命名管道 (FIFO)

提供一个路径名与之关联,以文件形式存在于文件系统中

持久化

有属主(owner)和访问权限

只要能访问该路径的进程都可以通过FIFO通信

严格遵循先进先出(First In First Out)

不支持诸如lseek()等文件定位操作

#include <sys/types.h>

#include <sys/stat.h>

int mkfifo(const char *pathname, mode_t mode);

pathname: 文件路径名

mode: 用来规定FIFO的读写权限

返回值:成功为0,失败为-1

两个实例

无名管道

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define READ 0
#define MSGSIZE 16
#define WRITE 1

int main(int argc,char *argv[]){
int p[2],bytes;
pid_t pid;

if(pipe(p)==-1){
perror("pipe call");
exit(1);
}

if((pid = fork())==-1){
perror("fork");
exit(1);
}
if(pid !=0){
close(p[READ]);
dup2(p[WRITE],1);
close(p[WRITE]);
execlp(argv[1],argv[1],NULL);
}
else{
close(p[WRITE]);
dup2(p[READ],0);
close(p[READ]);
execlp(argv[2],argv[2],NULL);
}

}


有名管道

server.c ./filename & 模拟守护进程运行

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

#define MSGSIZE 65

char *fifo="myfifo";

int main(int argc,char *argv[]){
int fd,i,nwrite;
char msgbuf[MSGSIZE+1];
if(argc>2){
printf("Usage:receive message &\n");
exit(1);
}
if(mkfifo(fifo,0666)==-1){
if(errno!=EEXIST){
perror("receiver:mkfifo");
exit(6);
}
}
if((fd=open(fifo,O_RDWR))<0){
perror("fifo open problem");
exit(3);
}
for(;;){
if(read(fd,msgbuf,MSGSIZE+1)<0){
perror("problem in reading");
exit(5);
}
printf("\n Message Received: %s\n",msgbuf);
fflush(stdout);
}
}

}


client.c

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <fcntl.h>

#define MSGSIZE 65

char *fifo = "myfifo";

int main(int argc,char *argv[]){
int fd,i,nwrite;
char msgbuf[MSGSIZE+1];

if(( fd = open(fifo,O_WRONLY | O_NONBLOCK)) < 0){
perror("fifo open error");
exit(1);
}
for(i = 1; i<argc;i++){
if(strlen(argv[i])>MSGSIZE){
printf("Message with Prefix %.*s Too long\n",10,argv[i]);
fflush(stdout);
continue;
}
strcpy(msgbuf,argv[i]);
if((nwrite = write(fd,msgbuf,MSGSIZE+1))==-1){
perror("Error in Writing");
exit(2);
}
}
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐