c++ 里用 alarm函数

夏尘 2015-10-18 05:07:03
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<string>
#include <iostream>
using namespace std;

void handler(int)
{
string szBuf;
time_t timer = time(NULL);
strftime(szBuf, sizeof(szBuf), "%Y-%m-%d %H:%M:%S", localtime(&timer));
printf("%s/n", szBuf);
signal(SIGALRM, handler); //让内核做好准备,一旦接受到SIGALARM信号,就执行 handler
alarm(1800);
}



int main()
{
handler();
while(1)
;
return 0;
}

错误信息:
1.cpp: In function 'void handler(int)':
1.cpp:13: error: cannot convert 'std::string'
1.cpp:14: warning: cannot pass objects of non-
1.cpp: In function 'int main()':
1.cpp:8: error: too few arguments to function
1.cpp:26: error: at this point in file


...全文
313 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
KEN123123 2015-10-18
  • 打赏
  • 举报
回复
#include<unistd.h>
#include<signal.h>
#include<stdio.h>
#include<string>
#include <iostream>
using namespace std;

void handler(int)
{
    char szBuf[100];
    time_t timer = time(NULL);
    strftime(szBuf, sizeof(szBuf), "%Y-%m-%d %H:%M:%S", localtime(&timer));
    printf("%s/n", szBuf);	
}

 

int main()
{

   signal(SIGALRM, handler); //让内核做好准备,一旦接受到SIGALARM信号,就执行 handler
    while(1)
  {
   alarm(1800);
  }
     
     return 0;
}
刚看的这些内容,不知道改得对不对,你试试吧。
fefe82 2015-10-18
  • 打赏
  • 举报
回复
引用 5 楼 u012598124 的回复:
[quote=引用 3 楼 fefe82的回复:]你的 handler 是有一个参数的啊,你的 main() 里的 hander(); 是什么意思?调用时要有一个实参的。
能不能麻烦您直接帮我写一个alarm函数的小例子可以嘛。每半小时发送信号。[/quote] 没用过,所以只能给你解释编译错误。
夏尘 2015-10-18
  • 打赏
  • 举报
回复
引用 3 楼 fefe82的回复:
你的 handler 是有一个参数的啊,你的 main() 里的 hander(); 是什么意思?调用时要有一个实参的。
能不能麻烦您直接帮我写一个alarm函数的小例子可以嘛。每半小时发送信号。
夏尘 2015-10-18
  • 打赏
  • 举报
回复
引用 3 楼 fefe82 的回复:
你的 handler 是有一个参数的啊,你的 main() 里的 hander(); 是什么意思?调用时要有一个实参的。
1.cpp: In function 'void handler()': 1.cpp:19: error: invalid conversion from 'void (*)()' to 'void (*)(int)' 1.cpp:19: error: initializing argument 2 of 'void (* signal(int, void (*)(int)))(int)' 把handler里的int去掉 就这样了 我就是想让他没有参数 直接调用的...之前看一个帖子 说这个错误 加个int 就好了
fefe82 2015-10-18
  • 打赏
  • 举报
回复
你的 handler 是有一个参数的啊,你的 main() 里的 hander(); 是什么意思?调用时要有一个实参的。
夏尘 2015-10-18
  • 打赏
  • 举报
回复
引用 1 楼 fefe82 的回复:
你需要的不是 string szBuf, 而是 char szBuf[100]。
1.cpp: In function 'int main()': 1.cpp:8: error: too few arguments to function 'void handler(int)' 1.cpp:26: error: at this point in file 改成char szBuf[100]后 我这是复制了一个.c的代码 直接放入.cpp里了
fefe82 2015-10-18
  • 打赏
  • 举报
回复
你需要的不是 string szBuf, 而是 char szBuf[100]。

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧