################### fifo.h #################
#ifndef FIFO_H
#define FIFO_H
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVER_FIFO "fifo_server"
#define FIFOMODE (O_CREAT | O_RDWR | O_NONBLOCK | S_IRUSR | S_IWUSR)
#define UMASK 0
struct simple_message {
pid_t sm_clientpid;
char sm_data[100];
};
#endif
############### server.c #####################
#include "fifo.h"
int main()
{
int fd_server, fd_client, fd_server_w=-1, i;
ssize_t nread;
struct simple_message msg;
char fifo_name[100];
printf("server started\n");
if (mkfifo(SERVER_FIFO, UMASK | FIFOMODE)==-1 && errno!=EEXIST) {
perror("make fifo error\n");
exit(0);
}
if ((fd_server = open(SERVER_FIFO, O_RDONLY)) < 0) {
perror("open error\n");
exit(1);
}
if ((fd_server_w = open(SERVER_FIFO, O_WRONLY)) < 0) {
perror("open error\n");
exit(1);
}
while(1) {
if ((nread = read(fd_server, &msg, sizeof(msg))) < 0) {
perror("read error\n");
exit(2);
}
for (i=0; msg.sm_data[i] != '\0'; i++)
msg.sm_data[i] = toupper(msg.sm_data[i]);
snprintf(fifo_name, sizeof(fifo_name), "fifo%ld", (long)msg.sm_clientpid);
if ((fd_client = open(fifo_name, O_WRONLY)) < 0) {
perror("open error\n");
exit(1);
}
if (write(fd_client, &msg, sizeof(msg)) < 0) {
perror("write error");
exit(1);
}
if (close(fd_client) < 0) {
perror("close error\n");
exit(1);
}
}
if (close(fd_client) < 0 || close(fd_server_w) < 0) {
perror("close error\n");
exit(1);
}
return 0;
}
############### client.c #################################3
#include "fifo.h"
int main()
{
int fd_server, fd_client = -1, i, fd_client_w=-1;
ssize_t nread;
struct simple_message msg;
char fifo_name[100];
char *work[] = {
"appleasauce",
"tiger",
"mountain",
NULL
};
printf("client %ld started\n", (long)getpid());
msg.sm_clientpid = getpid();
snprintf(fifo_name, sizeof(fifo_name), "fifo%ld", (long)msg.sm_clientpid);
if (mkfifo(fifo_name, UMASK | FIFOMODE)==-1 && errno != EEXIST) {
perror("make fifo error\n");
exit(0);
}
if ((fd_server = open(SERVER_FIFO, O_WRONLY)) < 0) {
perror("open error\n");
exit(1);
}
for (i=0; work[i]!=NULL; i++) {
strcpy(msg.sm_data, work[i]);
if (write(fd_server, &msg, sizeof(msg)) < 0) {
perror("write error\n");
exit(1);
}
if (fd_client == -1) {
if ((fd_client = open(fifo_name, O_RDONLY)) < 0) {
perror("open error\n");
exit(1);
}
}
if (fd_client_w == -1) {
if ((fd_client_w = open(fifo_name, O_WRONLY)) < 0) {
perror("open error\n");
exit(1);
}
}
if ((nread = read(fd_client, &msg, sizeof(msg))) < 0) {
perror("read error\n");
exit(1);
}
printf("client %ld: %s ----> %s\n", (long)getpid(), work[i], msg.sm_data);
}
if (close(fd_server)<0 || close(fd_client_w)<0 || close(fd_client)<0 || unlink(fifo_name)<0) {
perror("close error\n");
exit(1);
}
printf("Client %ld done\n", (long)getpid());
return 0;
}
阅读(1890) | 评论(0) | 转发(0) |