clienta.c
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
// 定义信息量全局变量
sem_t sem_send;
sem_t sem_get;
// 开两个线程,分别进行接收和发送:
void *send(void *argv)
{
char *buffer_send = (char *)argv;
// 定义fifo(管道)路径
char *FIFO_PATH = "/home/hqyj/Myfifo/client_a";
// 打开文件流,此端为发送端
int fd = open(FIFO_PATH, O_WRONLY);
if (-1 == fd)
{
perror("open");
pthread_exit(NULL);
}
puts("myfifoA open success!");
while (1)
{
fgets(buffer_send, 256, stdin);
buffer_send[strlen(buffer_send) - 1] = '\0';
write(fd, buffer_send, strlen(buffer_send));
}
close(fd);
}
void *get(void *argv)
{
char *buffer_get = (char *)argv;
// 定义fifo(管道)路径
char *FIFO_PATH = "/home/hqyj/Myfifo/client_b";
// 打开文件流,此端为收端
int fd = open(FIFO_PATH, O_RDONLY);
if (-1 == fd)
{
perror("open");
pthread_exit(NULL);
}
puts("myfifoB open success!");
while (1)
{
memset(buffer_get, 0, 256);
read(fd, buffer_get, 256);
printf("RECV:%s\n", buffer_get);
}
close(fd);
}
int main()
{
// 定义缓冲区
char buffer_send[256];
char buffer_get[256];
pthread_t tid_send, tid_get;
// 创建线程
if (0 != pthread_create(&tid_send, NULL, send, buffer_send))
{
perror("tid creat");
}
if (0 != pthread_create(&tid_get, NULL, get, buffer_get))
{
perror("tid creat");
}
// 同步进程线程
if (0 != pthread_join(tid_send, NULL))
{
perror("join");
}
if (0 != pthread_join(tid_get, NULL))
{
perror("join");
}
return 0;
}
client.b
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <semaphore.h>
#include <pthread.h>
sem_t sem_send;
sem_t sem_get;
// 开两个线程,分别进行接收和发送:
void *send(void *argv)
{
char *buffer_send = (char *)argv;
// 定义fifo(管道)路径
char *FIFO_PATH = "/home/hqyj/Myfifo/client_b";
// 打开文件流,此端为发送端
int fd = open(FIFO_PATH, O_WRONLY);
if (-1 == fd)
{
perror("open");
pthread_exit(NULL);
}
puts("myfifoA open success!");
while (1)
{
fgets(buffer_send, 256, stdin);
buffer_send[strlen(buffer_send) - 1] = '\0';
write(fd, buffer_send, strlen(buffer_send));
}
close(fd);
}
void *get(void *argv)
{
char *buffer_get = (char *)argv;
// 定义fifo(管道)路径
char *FIFO_PATH = "/home/hqyj/Myfifo/client_a";
// 打开文件流,此端为收端
int fd = open(FIFO_PATH, O_RDONLY);
if (-1 == fd)
{
perror("open");
pthread_exit(NULL);
}
puts("myfifoB open success!");
while (1)
{
// 定义缓冲区
memset(buffer_get, 0, 256);
read(fd, buffer_get, 256);
printf("RECV:%s\n", buffer_get);
}
close(fd);
}
int main()
{ // 定义缓冲区
char buffer_send[256];
char buffer_get[256];
pthread_t tid_send, tid_get;
// 创建线程
if (0 != pthread_create(&tid_send, NULL, send, buffer_send))
{
perror("tid creat");
}
if (0 != pthread_create(&tid_get, NULL, get, buffer_get))
{
perror("tid creat");
}
// 同步进程线程
if (0 != pthread_join(tid_send, NULL))
{
perror("join");
}
if (0 != pthread_join(tid_get, NULL))
{
perror("join");
}
return 0;
}