("\\\\.\\pipe\\ethan",PIPE_ACCESS_DUPLEX|FILE_FLAG_OVERLAPPED,
0,1,1024,1024,0,
NULL);
由于FIFO是作为一个有名文件存在于文件系统中的,需要确认你是否有创建文件的权限。看你上面写的文件的路径好像有问题哦。
下面是UNIX环境命名管道的例子。
头文件:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_FIFO_NAME "/opt/chengxs/temp/fifo/serv_fifo" /*服务专用的fifo*/
#define CLIENT_FIFO_NAME "/opt/chengxs/temp/fifo/client_%d_fifo" /*客户专用的fifo*/
struct data_to_pass
{
pid_t client_pid;
char text_data[256-1];
};
客户端:
/*
*客户程序
*/
#include"cliserv.h"
int main()
{
int server_fifo_fd,client_fifo_fd;
struct data_to_pass my_request;
int times_to_send;
char client_fifo_name[256];
pid_t mypid;
/*打开服务管道*/
server_fifo_fd = open(SERVER_FIFO_NAME,O_WRONLY);
if(server_fifo_fd == -1)
{
perror("Sorry,no server");
exit(1);
}
/*创建以进程ID命名的客户接收管道*/
mypid = getpid();
sprintf(client_fifo_name,CLIENT_FIFO_NAME,mypid);
if(mkfifo(client_fifo_name,0777) == -1)
{
perror(client_fifo_name);
exit(2);
}
/*向服务进程连续发送和接收五次数据*/
for(times_to_send=0;times_to_send<5;times_to_send++)
{
sprintf(my_request.text_data,"Hello from %d,%d",mypid,times_to_send);
my_request.client_pid = mypid;
/*向服务进程发出请求*/
printf("%d send: %s,",mypid,my_request.text_data);
write(server_fifo_fd,&my_request,sizeof(my_request));
/*从服务进程接收回答,打开客户有名管道*/
client_fifo_fd = open(client_fifo_name,O_RDONLY);
if(client_fifo_fd!=-1)
{
if(read(client_fifo_fd,&my_request,sizeof(my_request))>0)
{
printf("%d received: %s\n",mypid,my_request.text_data);
}
close(client_fifo_fd);
}
}
close(server_fifo_fd);
unlink(client_fifo_fd);
exit(0);
}
服务端:
/*
*服务程序
*/
#include"cliserv.h"
int main()
{
int server_fifo_fd,client_fifo_fd;
struct data_to_pass my_data;
int nbytes;
char client_fifo_name[256];
char * tmp_char_ptr;
/*创建并打开服务FIFO*/
mkfifo(SERVER_FIFO_NAME,0777);
server_fifo_fd = open(SERVER_FIFO_NAME,O_RDONLY);
if(server_fifo_fd == -1)
{
perror("Server info failed!");
exit(1);
}
/*客户请求排队*/
sleep(10);
do
{
/*接收来自客户的请求*/
nbytes = read(server_fifo_fd,&my_data,sizeof(my_data));
if(nbytes>0)
{
/*处理客户请求*/
tmp_char_ptr = my_data.text_data;
while(*tmp_char_ptr)
{
*tmp_char_ptr = toupper(*tmp_char_ptr);
tmp_char_ptr++;
}
/*返回处理过的数据*/
sprintf(client_fifo_name,CLIENT_FIFO_NAME,my_data.client_pid);
client_fifo_fd = open(client_fifo_name,O_WRONLY);
if(client_fifo_fd != -1)
{
write(client_fifo_fd,&my_data,sizeof(my_data));
close(client_fifo_fd);
}
}
}while(nbytes>0);
close(server_fifo_fd);
unlink(SERVER_FIFO_NAME);
return 0;
}
运行时:
先运行服务端程序,在运行客户端程序。