// 20170224 11:58
// gcc winter.c
// ./a.out
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#define NUM_THREADS 3 // 75% CPU on [ OS X 10.11.6 MacBook Pro (Retina, 13-inch, Early 2015) ]
#define NUM_SECONDS 60
static int g_run = 1;
// Charging: No
// Charging: No
// 说明:用于判断是否已经在充电了。
static int is_charging()
{
int ret = 0;
FILE* fstream = NULL;
char buff[1024];
memset(buff, 0, sizeof(buff));
if ( NULL == (fstream = popen("system_profiler SPPowerDataType | grep 'Charging: '","r")) )
{
return -1;
}
while ( NULL != fgets(buff, sizeof(buff), fstream) )
{
if ( strlen(buff) > 20 ) // 因为有两行符合条件的,这里只选择一行判断即可。
{
printf("%s", buff);
if ( NULL != strstr(buff,"Yes") )
{
ret = 1; // 正在充电
}
}
memset(buff, 0, sizeof(buff));
}
pclose(fstream);
fstream = NULL;
return ret;
}
static void* cpu(void* args)
{
int i = 0;
float j = 0;
while (g_run)
{
i += 5;
i -= 3;
i *= 5;
i /= 3;
j += 5.1;
j -= 3.2;
j *= 5.3;
j /= 3.4;
}
return NULL;
}
// 冬天MBP经常充不进电,原因是温度太低。平时喜欢通过运行flash程序让电脑发热,比如看看优酷视频什么的,但是如果是在公司上班时间呢?看片总不太好吧……
int main(void)
{
pthread_t threads[NUM_THREADS];
int t = 0;
g_run = 1;
for (t = 0; t < NUM_THREADS; ++t)
{
if ( 0 != pthread_create(&threads[t], NULL, cpu, NULL) ) // CPU动起来,温度升上来。
{
return -1;
}
}
while ( 1 != is_charging() ) // 如果温度够了,电池已经在充电了,那就退出这个程序吧。否则间隔 NUM_SECONDS 秒之后再检测一次。
{
sleep(NUM_SECONDS);
}
g_run = 0;
for (t = 0; t < NUM_THREADS; ++t)
{
pthread_join(threads[t], NULL);
}
return 0;
}