我有以下代码:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
time_t result;
char hostname[10] = "ws45new";
char graphite[10] = "127.0.0.1";
char buf[1024];
int n = 0;
int num = 0;
int graphiteport = 2003;
while (1 == 1)
{
result = time(NULL);
n = n + 1;
if (n >= 100)
n = 0;
printf("n %d", n);
// snprintf(buf, sizeof(buf), "echo "stats.ws45new.test %d %d " | nc 127.0.0.1 2003", n, result);
num = sprintf(buf, "echo "stats.ws45new1.test %d %d " | nc 127.0.0.1 2003", n, result);
system(buf);
printf("n %s", buf);
sleep(2);
}
return 0;
}
这应该会产生类似锯齿波的信号,这只是为了测试。我的问题是,当我运行这个程序时,它什么都不做。
如果我点击Ctrl-C来停止它,程序会在while循环中迭代一次。它应该向石墨服务器发送一些统计数据,我用它来了解石墨是如何工作的。根据我所看到的,它与连接函数sprintf
有关(snprintf
也以相同的方式工作)。
如果我注释掉那行,它会正确工作,并生成我想要的数字(以及epoch),但我需要连接才能将所需的动态信息发送到石墨。
如果有人知道为什么这些串联函数不尊重while函数,请告诉我,因为我真的很好奇。此外,我对其他建议持开放态度,但我宁愿不深入研究,比如创建套接字,不使用nc和system,因为我对C语言不太熟悉。
程序很可能在系统调用中被卡住。
您打印出的文本没有尾部换行符,因此它将保留在缓冲区中,直到打印出换行符,这是在system
调用之后完成的。