Android11 native looper 使用入门

这篇博客演示了一个C++程序,通过创建管道和使用Looper处理来自子进程的消息。子进程在延迟2秒后向管道写入数据,父进程读取并处理这些消息,直到达到指定的超时时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <chrono>
#include <thread>

#include <utils/Trace.h>

#include <stdio.h>
#include <pthread.h>

#include <stdlib.h>
#include <unistd.h>
#include <thread>
#include <iostream>
#include <stdint.h>
#include <sys/types.h>
#include <utils/Looper.h>
#include <time.h>
#include <unistd.h>
#include <utils/Looper.h>
#include <utils/StopWatch.h>
#include <utils/Timers.h>
#include <thread>
#include <utility>

#include <utils/threads.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
 #include <fcntl.h>

using namespace std;
using namespace android;

int staticHandler(int fd, int events, void *data) {
	char buf[1];
	cout << "staticHandler" << endl;
	while(::read(fd, buf, 1)>0){
		::write(STDOUT_FILENO, buf, 1);
	}
	cout << "\nwait next msg" << endl;
	return 1;
}

int main(int, const char**) {
	int pipefd[2];

	pid_t cpid;
	if (pipe(pipefd) == -1) {
		perror("pipe");
		exit(EXIT_FAILURE);
	}

	sp < Looper > looper = new Looper(false);
	int result = looper->addFd(pipefd[0], 0, Looper::EVENT_INPUT, staticHandler,
			nullptr);
	if (result < 0) {
		cout << "result  :" << result << endl;
		perror(NULL);
		return -1;
	}
	cout << "result  :" << result << endl;
	cpid = fork();
	if (cpid == -1) {
		perror("fork");
		exit(EXIT_FAILURE);
	}
	if (cpid == 0) { /* Child */
		sleep(2);
		close(pipefd[0]); /* Close unused read end */
		for(int i=0;i<5;i++){
			char a[] = "123456";
				write(pipefd[1], a, strlen(a));
				sleep(1);
		}

		close(pipefd[1]); /* Reader will see EOF */
		cout << "child exit now" << endl;
		return 0;
	} else { /* Parent */
		int  flag =fcntl(pipefd[0],F_GETFL);
		fcntl(pipefd[0],F_SETFL ,flag | O_NONBLOCK);

		StopWatch stopWatch("pollOnce");
		while (1) {
			cout << "pollOnce" << endl;
			int result = looper->pollOnce(1000*3);
			if(result == Looper::POLL_TIMEOUT){
				cout << "timeout" << endl;
				break;
			}
		}
		int32_t elapsedMillis = ns2ms(stopWatch.elapsedTime());
		cout << elapsedMillis << endl;
	}
	wait(NULL);
	cout << "end" << endl;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值