libubox中uloop库的使用

uloop.c是libubox的一个小模块,简化了编程


1. socket 使用

#include ""

struct uloop_fd ufd;	//创建uloop_fd全局变量

static void fd_handler(struct uloop_fd *u, unsigned int ev)
{
	if(recvfrom(u->fd, ...)) == -1) {
	
	} else {
		//do your work
	}
}

int main()
{
	//
	int socket = socket(....);
	
	ufd.fd = socket;
	
	uloop_init();			//使用库初始化	
	
	ufd.cb = fd_handler;

	uloop_fd_add(&ufd, ULOOP_READ));

	uloop_run();
}

2. 定时器使用

#include ""

struct uloop_timeout timeout;	//创建uloop_timeout全局变量

int frequency = 5; //每隔5秒超时一次

static void timeout_cb(struct uloop_timeout *t)
{
	//do your work
	
	uloop_timeout_set(t, frequency * 1000);//设置下次的超时时间
}

int main()
{	
	uloop_init();			//使用库初始化	
	
	timeout.cb = timeout_cb;
	
	uloop_timeout_set(t, frequency * 1000);//设置下次的超时时间

	uloop_run();
}

3. 子进程的使用

其作用是在子进程中调用rsync命令进行文件同步,子进程退出后调用rsync_complete回调函数

#include ""

static struct uloop_process rsync;	//创建rsync全局变量

static void rsync_complete(struct uloop_process *proc, int ret)
{
	//do something where child exit;
	printf("rsync work is complete\n");
}

function fun() 
{
	char *argv[]={"rsync", "-az", "rsync://XYZ@192.168.26.99/www","/root/www/","--password-file=/root/rsync.secrets", NULL};
	rsync.cb = rsync_complete;
	rsync.pid = fork();

	if (!rsync.pid) {
		/* This is child process*/
		execvp(argv[0], argv);
		fprintf(stderr, "fork failed\n");
		exit(-1);
	}

	if (rsync.pid <=0) {
		fprintf(stderr, "fork failed2\n");
		return -1;
	}

	uloop_process_add(&rsync);

}


int main()
{
	
	.....
	
	uloop_init();	//使用库前进行初始化
	
	fun();
	
	uloop_run();
	
}

以上是简单的伪代码演示。uloop只适合于单线程中的任务,多线程会有bug。

  • 2
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值