#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;
}
Android11 native looper 使用入门
于 2022-12-18 22:28:10 首次发布