//pthread线程等待数据输入并通过管道发送将数据发送出去,另一线程thread1则时刻等待发送过来的数据,并对数据进行解析。
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include <string.h>
#include <errno.h>
pthread_t pthread;
pthread_t pthread1;
#define LEN 50
typedef struct pipe_object_struct {
pthread_mutex_t mutex;
int pipes[2];
} pipe_object, *pipe_handle;
pipe_handle pipe_create(void);
int pipe_get(pipe_handle h_pipe, void *data, const int num);
int get_data_from_pipe(void *buf,int len);
void pipe_handld();
static pipe_handle Dat;
pipe_handle pipe_create(void) //管道创建
{
pipe_handle h_pipe;
h_pipe = calloc(1, sizeof(pipe_object));
if (h_pipe == NULL) {
printf( "Failed to allocate space for pipe object\n");
return NULL;
}
if (pipe(h_pipe->pipes)) {
free(h_pipe);
return NULL;
}
return h_pipe;
}
int pipe_get(pipe_handle h_pipe, void *data, const int num) //得到管道中的buf
{
int ret = 0;
ret = read(h_pipe->pipes[0], data, num);
if (ret != num) {
perror("pipe read");
return -1;
} else {
}
return 0;
}
int pipe_put(pipe_handle h_pipe, void *data, int num)//输入buf
{
int ret= 0;
ret = write(h_pipe->pipes[1], data, num);
if (ret != num) {
return -1;
} else {
}
return 0;
}
int put_data_to_pipe(void *buf,int len)//要发送的buf
{
//char buf[]="a";
return pipe_put(Dat,buf,len);
}
int get_data_from_pipe(void*buf,const int len)//得到buf
{
return pipe_get(Dat,buf,len);
}
void pipe_handld(){ //接收到数据,并解析
printf("pipe_handld thread create!!!!!!!!!!!!!!!\n");
while(1){
char buf[LEN];
if(get_data_from_pipe(buf,LEN)==0){
switch(buf[0]){
case 'a':
printf("get a\n");
break;
case 'b':
printf("get b\n");
break;
case 'c':
printf("get c\n");
break;
default:
printf("not exit\n");
break;
}
}
bzero(buf,LEN);
}
printf("exit pipe_handld\n");
}
void pipe_input(){ //输入buf
char buf[LEN];
while(1){
fgets(buf,LEN,stdin);
put_data_to_pipe(buf,LEN);
//sleep(3);
//put_data_to_pipe(buf1,LEN);
bzero(buf,LEN);
}
return;
}
int main(void)
{
char buf1[]="b";
Dat=pipe_create();
pthread_create(&pthread1,NULL,(void *)&pipe_input,NULL);
pthread_create(&pthread,NULL,(void *)&pipe_handld,NULL);
printf("after main\n");
while(1){
sleep(1);
}
return 0;
}
执行结果: