Linux 线程之间用管道通信,出了个比较2的问题,贴代码,大家瞧瞧啊
#include <string.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <unistd.h>
#include<stdio.h>
#include<pthread.h>
#include <iostream>
using namespace std;
int fd[2]= {-1, -1};
typedef struct Message
{
unsigned int command;
char ch;
}Msg;
bool isNotEmpty(int fdR)
{
struct pollfd pfd;
pfd.fd = fd[0];
pfd.events = POLLIN;
pfd.revents = 0;
if(pfd.fd <0)
{
cout<<"read descriptor not initialized!"<<endl;
return false;
}
if(-1 == poll(&pfd, 1, 1000))
{
cout<<"poll error"<<endl;
return false;
}
if(pfd.revents & POLLIN)
{
return true;
}
return false;
}
void put(Msg *msg)
{
if(fd[1] > 0)
{
int err = write(fd[1], (char*)msg, sizeof(*msg));
printf("wirte message :%d\n", msg->command);
printf("wirte message :%c\n", msg->ch);
if(err < 0)
{
cout<<"write pipe failed!"<<endl;
}
}
else
{
cout<< "read descriptor not initialized"<<endl;
}
}
int get()
{
char chstr[10];
int len = 0;
int err = read(fd[0], chstr, sizeof(chstr));
if(err < 0)
{
cout<<"read pipe failed"<<endl;
}
len = strlen(chstr);
chstr[len+1] = '\0';
Msg *msg = (Msg*)chstr;
printf("recevie message :%d\n", msg->command);
printf("recevie message :%c\n", msg->ch);
return msg->command;
}
void *recevieMsg(void *data)
{
while(1)
{
if(isNotEmpty(fd[0]))
{
// 写线程,只写入了15个数据;
if(get() == 14)
break;
}
else
{
cout<<"pipe is empty!!!"<<endl;
}
}
}
void *sendMsg(void *data)
{
Msg msg;
// 向管道写入15个数据;
for(int i=0; i<15; i++)
{
msg.command = i;
msg.ch = 'a' + i;
put(&msg);
//usleep(10);
}
}
int main()
{
void *retval;
pthread_t pth_a, pth_b;
if(pipe(fd)<0)
{
cout<<"create pipe failed"<<endl;
}
pthread_create(&pth_b, NULL, sendMsg, NULL);
pthread_create(&pth_a, NULL, recevieMsg, NULL);
pthread_join(pth_a, &retval);
pthread_join(pth_b, &retval);
close(fd[1]);
close(fd[0]);
return 0;
}