定义数组函数集合:
void (*fun_hangld[])()={ //函数的存放集合
Fun1,
Fun2,
Fun3,
Fun4
};
通过while(1){(*fun_hangld[buf[0]])();}一直读取buf[0]的值,来确定是进行那个函数。这种思想在进行模块化时很好用,比如按键来控制屏幕之间的对应关系,一个按键值,代表不同界面的显示内容,把要显示的每一页面内容分为一个个函数来对应,buf[]的值就代表按键要选择的页面,可以实现高效简洁循环显示。
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#include<stdlib.h>
#include <string.h>
#include <errno.h>
pthread_t pthread;
pthread_t pthread1;
typedef struct pipe{
int list;
int pipes[2];
}pipeobj,*Ppipe;
Ppipe pipe_create();
void fun(void);
Ppipe PIPE;
int LIST;
void Fun1(void);
void Fun2(void);
void Fun3(void);
void Fun4(void);
void (*fun_hangld[])()={ //函数的存放集合
Fun1,
Fun2,
Fun3,
Fun4
};
void Fun1(void){
printf("in Fun1 \n");
return;
}
void Fun2(void){
printf("in Fun2 \n");
return;
}
void Fun3(void){
printf("in Fun3 \n");
return;
}
void Fun4(void){
printf("in Fun4 \n");
return;
}
Ppipe pipe_create()
{
Ppipe h_pipe;
h_pipe=calloc(1,sizeof(pipeobj));
if(NULL==h_pipe){
perror("h_pipe");
return NULL;
}
if(pipe(h_pipe->pipes)<0){
free(h_pipe);
return NULL;
}
return h_pipe;
}
void fun_write(void)
{
int buf[10];
if(NULL==PIPE){
perror("PIPE");
exit(-1);
}
while(1)
{
bzero(buf,sizeof(buf));
//fgets(buf,sizeof(buf),stdin);
scanf("%d",&buf[0]); //通过buf[0]的值来调用想要调用的函数
write(PIPE->pipes[1],buf,sizeof(buf));
}
return;
}
void fun_read(void)
{
int buf[10];
while(1)
{
int count=0;
bzero(buf,sizeof(buf));
count=read(PIPE->pipes[0],buf,sizeof(buf));
if(count<0)
{
continue;
}
printf("read buf的内容是:%d\n",buf[0]);
(*fun_hangld[buf[0]])(); //不断读取buf[0]的值,来决定调用哪个函数
}
printf("6\n");
return;
}
int main(void)
{
PIPE=pipe_create();
pthread_create(&pthread,NULL,(void *)&fun_write,NULL);
pthread_create(&pthread1,NULL,(void *)&fun_read,NULL);
printf("after main\n");
while(1){
sleep(1);
}
return 0;
}
编译执行结果: