include
include
include
include
include
include
include
include
include
include
include
include
define MAXLINE 64
int Array_Printf(char *data ,int len ,int HexOrDec)
{
int i=0;
if(data == NULL)
{
return -1;
}
printf("\n----------------------------------------\n");
for(i=0;i<len;i++)
{
if(HexOrDec==0)
printf("%02X ",(unsigned char)data[i]);
else
printf("%02d ",(unsigned char)data[i]);
}
printf("\n----------------------------------------\n");
return 0;
}
int fd[2];
void Thread_Deal(void *arg){
char line[MAXLINE];
int n,i;
int fd = (int)arg;
while(1)
{
memset(line,0,sizeof(line));
n = read(fd, line, MAXLINE);//fd[0]为管道读,默认阻塞
Array_Printf(line,MAXLINE,0);
printf("n = %d\n",n);
sleep(2);
}
}
int ret=10;
void Thread_Send(void *arg){
char tem[MAXLINE];
int n,len,i=0;
int fd = (int)arg;
while(1)
{
if(i++>=10)
{
pthread_exit((void*)&ret);
}
printf("i = %d\n",i);
for(n =0; n<64;n++)
{
tem[n]=n;
}
len = write(fd,tem,sizeof(tem));
printf("write len:%d\n",len);
sleep(1);
}
}
int main(void) {
unsigned char *reg;
if (pipe(fd) < 0)
perror(“pipe error”);
printf(“0: %d,1: %d \n”,fd[0],fd[1]);
int flags = fcntl(fd[0],F_GETFL);
fcntl(fd[0] ,F_SETFL ,flags | O_NONBLOCK);
flags = fcntl(fd[1],F_GETFL);
fcntl(fd[1] ,F_SETFL ,flags | O_NONBLOCK);
pthread_t thread_pool[2];
pthread_create(&thread_pool[0], NULL, (void*)Thread_Deal, &fd[0]);
pthread_create(&thread_pool[1], NULL, (void*)Thread_Send, &fd[1]);
pthread_join(thread_pool[1], (void *)®);
while(1)
{
printf("reg = %d \n",*(unsigned char *)reg);
sleep(1);//100ms
}
}
需要注意pthread_exit((void*)&ret) 参数为全局变量,因为线程函数退出会导致线程栈回收。