一开始上传了.rar 文件,大家看着不方便,所以直接将代码列出:
下面是我的loop.cpp文件:
#include "loop.h"
#include <qlabel.h>
#include <qpushbutton.h>
#include <qstring.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
/*声明信号处理函数,此函数在进程收到信号的时候调用*/
static void sig_handler(int signo);
long lastsec,countsec; /*这两个变量分别用来保存上一秒的时间和总共花去的时间*/
int i; /*label控件中要显示的变量*/
QLabel *girlPixmapLabel;
MyHelloForm *hello;
MyHelloForm::MyHelloForm( QWidget* parent, const char* name, WFlags fl)
:HelloBaseForm(parent, name, fl)
{
connect(helloPushButton,SIGNAL(clicked()),this,SLOT(timer()));
connect(eddyPushButton,SIGNAL(clicked()),this,SLOT(showMe()));
}
MyHelloForm::~MyHelloForm()
{
}
void timer(void)
{
struct itimerval v; /*定时器结构体*/
long nowsec,nowusec; /*当前时间的秒数和微秒数*/
/*注册SIGUSR1和SIGALARM信号的处理函数为sig_handler*/
if(signal(SIGUSR1,sig_handler)==SIG_ERR)
{
girlPixmapLabel->setText( "Unable to create handler for SIGUSR1" );
exit(0);
}
if(signal(SIGALRM,sig_handler)==SIG_ERR)
{
girlPixmapLabel->setText( "Unable to create handler for SIGALRM" );
exit(0);
}
/*初始化定时器初值和当前值*/
v.it_interval.tv_sec=9;
v.it_interval.tv_usec=9000000;
v.it_value.tv_sec=9;
v.it_value.tv_usec=9000000;
/*调用setitimer设置定时器,并将其挂到定时器链表上,这个函数的三个参数的含义分
别是设置ITIMER_REAL类型的定时器,要设置的值存放在变量v中,该定时器设置前的值
在设置后保存的地址,如果是这个参数为NULL,那么就放弃保存设置前的值*/
setitimer(ITIMER_REAL,&v,NULL);
lastsec=v.it_value.tv_sec;
countsec=0;
/*该循环首先调用getitimer读取定时器当前值,再与原来的秒数比较,当发现已经过了
一秒后产生一个SIGUSR1信号,程序就会进入上面注册过的信号处理函数*/
while(1)
{
getitimer(ITIMER_REAL,&v);
nowsec=v.it_value.tv_sec;
nowusec=v.it_value.tv_usec;
if(nowsec==lastsec-1)
{
/*每过一秒,产生一个SIGUSR1信号*/
raise(SIGUSR1);
lastsec=nowsec;
countsec++; /*记录总的秒数*/
}
}
}
/*信号处理函数*/
static void sig_handler(int signo)
{
switch(signo)
{
/*接收到的信号是SIGUSR1,使i累加1,然后调用sayHello()*/
case SIGUSR1:
i++;
hello->sayHello();
break;
/*定时器定时到达*/
case SIGALRM:
{
girlPixmapLabel->setText("Timer has been zero");
lastsec=countsec;
countsec=0;
break;
}
}
}
void MyHelloForm::sayHello()
{
girlPixmapLabel->clear();
girlPixmapLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken );
girlPixmapLabel->setNum(i);
girlPixmapLabel->setAlignment( AlignCenter );
}
void MyHelloForm::showMe()
{
girlPixmapLabel->clear();
girlPixmapLabel->setFrameStyle( QFrame::Panel | QFrame::Sunken );
girlPixmapLabel->setText( "Hello\n\nI am Bad Boy" );
girlPixmapLabel->setAlignment( AlignCenter );
}
下面是我的loop.h文件:
#ifndef MYHELLOFORM_H
#define MYHELLOFORM_H
#include "loop_base.h"
#include <qpixmap.h>
class MyHelloForm : public HelloBaseForm
{
Q_OBJECT
public:
MyHelloForm( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 );
virtual ~MyHelloForm();
// const QPixmap *eddy;
private slots:
void showMe();
void timer(void);
void sayHello();
};
#endif // MYHELLOFORM_H