您的位置:首页 > 其它

FIFO和线程的使用

2017-06-21 22:51 162 查看
做一个类似聊天的工具
第一个程序的代码

#include
#include
#include
#include
#include
#include
#include
#include

int res, r_fd, s_fd;
pthread_t th_r, th_w;
int kflag = 0;

void *thread_w()
{
int tmp;
char p[1000];
while(gets(p))
{
tmp = mkfifo("/ktmp/kfifo1", 0111);
if(tmp < -1)
printf("Create the fifo pipe failed\n");
s_fd = open("/ktmp/kfifo1", O_WRONLY, 0111);
write(s_fd, p, strlen(p) + 1);
close(s_fd);
}
}

void *thread_r()
{
int tmp;
char p[1000];
struct stat kstat;
while(1){
while((r_fd = open("/ktmp/kfifo2", O_RDONLY, 0111)) ==
-1);
if(kflag == 0)
{
printf("Connecting success\n");
kflag = 1;
}
stat("/ktmp/kfifo1", &kstat);
while((tmp = read(r_fd, p, 200)) == 0);
printf("%s\n", p);
close(r_fd);
unlink("/ktmp/kfifo2");
}
}

void main()
{
res = pthread_create(&th_w, NULL, thread_w, NULL);
if(res != 0)
printf("Create writing thread failed\n");
res = pthread_create(&th_r, NULL, thread_r, NULL);
if(res != 0)
printf("Create reading thread failed\n");
while(1);
}

第二个程序的代码

#include
#include
#include
#include
#include
#include
#include
#include

int res, r_fd, s_fd;
pthread_t th_r, th_w;
int kflag = 0;

void *thread_w()
{
int tmp;
char p[1000];
while(gets(p)){
tmp = mkfifo("/ktmp/kfifo2", 0111);
if(tmp < -1)
printf("Create the fifo pipe failed\n");
s_fd = open("/ktmp/kfifo2", O_WRONLY, 0111);
write(s_fd, p, strlen(p) + 1);
close(s_fd);
}
}

void *thread_r()
{
int tmp;
char p[1000];
struct stat kstat;
while(1){
while((r_fd = open("/ktmp/kfifo1", O_RDONLY, 0111)) ==
-1);
if(kflag == 0)
{
printf("Connecting success\n");
kflag = 1;
}
stat("/ktmp/kfifo1", &kstat);
while((tmp = read(r_fd, p, 200)) == 0);
printf("%s\n", p);
close(r_fd);
unlink("/ktmp/kfifo1");
}
}

void main()
{
res = pthread_create(&th_w, NULL, thread_w, NULL);
if(res != 0)
printf("Create writing thread failed\n");
res = pthread_create(&th_r, NULL, thread_r, NULL);
if(res != 0)
printf("Create reading thread failed\n");
while(1);
}

实现的结果就是

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: