首先创建一个server.c文件与client.c文件,使用Makefile将这两个文件管理起来。
Makefile文件:
.PHONY:all
all:server client
server:server.c
gcc $^ -o $@
client:client.c
gcc $^ -o $@
.PHONY:clean
clean:
rm server client
【server.c】模拟服务器端,运行后创建一个进程
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#define ERR_EXIT(m)\ //将报错与退出包成一个宏
do\
{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)
int main()
{
umask(0);
if(mkfifo("mypipe",0644)<0) //创建一个命名管道
ERR_EXIT("mkfifo");
int rfd=open("mypipe",O_RDONLY);
if(rfd<0)
ERR_EXIT("open");
char buf[1024];
while(1)
{
buf[0]=0;
printf("Please wait....\n");
size_t s=read(rfd,buf,sizeof(buf)-1);
if(s>0)
{
buf[s]=0;
printf("client say# %s\n",buf);
}
else if(s==0)
{
printf("client quit,exit now!\n");
exit(EXIT_SUCCESS);
}
else
{
ERR_EXIT("read");
}
}
close(rfd);
return 0;
}
这里有一个函数 umask( )简单介绍下:
头文件:#include< sys / stat.h>
umask函数为进程设置文件模式创建屏蔽字,并返回以前的值。函数原型为:
mode_t umask(mode_t cmask);
cmask是由下表列出的9个常量中的若干个按位“或”构成的
S_IRUSR 用户读
S_IWUSR 用户写
S_IXUSR 用户执行
S_IRGRP 组读
S_IWGRP 组写
S_IXGRP 组执行
S_IROTH 其他读
S_IWOTH 其他写
S_IXOTH 其他执行
【client.c】模拟客户端,运行后创建一个进程
#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<string.h>
#define ERR_EXIT(m)\
do\
{\
perror(m);\
exit(EXIT_FAILURE);\
}while(0)
int main()
{
int wfd=open("mypipe",O_WRONLY);
if(wfd<0)
{
ERR_EXIT("open");
}
char buf[1024];
int a=2; //message number
while(a--)
{
buf[0]=0;
printf("Please Enter# ");
fflush(stdout);
size_t s=read(0,buf,sizeof(buf)-1);
if(s>0)
{
buf[s]=0;
write(wfd,buf,strlen(buf));
}
else if(s<=0)
{
ERR_EXIT("read");
}
}
close(wfd);
return 0;
}
测试运行:
注:在运行时,要先运行server,再运行client。必须要server先创建出命名管道mypipe然后client才能打开。