我已经构建了一个 Geiger-Mueller 计数器,其输出连接到计算机并行物理端口 #3。
我有一个循环检查该端口上的事件。 2ms 时间范围内可能有 2-4 个脉冲。
此行之后 printf("Radiatie: %.4f uSv\n",(float)sievert);
我想以某种方式每 60 秒执行一次 mysql 插入查询...但是该查询执行时间不应干扰 for 循环。
欢迎任何帮助,谢谢!
#include <stdio.h>
#include <unistd.h>
#include <sys/io.h>
#include <time.h>
#define BASEPORT 0x378 /* lp1 */
static int var = 0;
static int C = 1;
static int CPM; /* pulse count */
static float sievert;
int main ()
{
time_t start_t, end_t; double diff_t;
if (ioperm(BASEPORT, 3, 1)) {perror("ioperm"); exit(1);}
outb(0, BASEPORT);
time(&start_t);
for( ; ; )
{
/* Read from port */
var = inb(BASEPORT +1);
if (var == 56)
{
/* 56 is the value of HIGH (pulse) */
CPM = C++;
printf("%d\n",CPM );
}
time(&end_t);
diff_t = difftime(end_t, start_t);
int b = (int) diff_t;
if (b == 60)
{
sievert = CPM * 0.0058; /* converting Counts per Minute in uSievert */
C = 1;
printf("Radiatie: %.4f uSv\n",(float)sievert);
time(&start_t);
}
/* end for */
}
}
最佳答案
您应该使用多线程环境,以便能够同时计数和运行 mysql 查询。您可以使用 fork()
和 pipe()
进行通信轻松完成此操作。
int comm[2];
pipe(comm);
if (pid) { // In parent process
int count;
int reading_loc = 0, current_read;
while (current_read = read(comm[0], &count + reading_loc, sizeof(int) - reading_loc)) {
reading_loc += current_read;
if (reading_loc == sizeof(int)) {
reading_loc = 0;
// GOT FULL VALUE IN COUNT.
// Run mysql query
}
}
} else { // In child process
while (true) {
// Do collection stuff
int value_to_send;
if (should_run_query) {
int current_write, writing_loc = 0;
while (current_write = write(comm[1], &value_to_send + writing_loc, sizeof(int) - writing_loc)) {
if (current_write == -1) {
// Error in the writing process. Be sad :(
}
writing_loc += current_write;
}
}
}
}
这是 fork 后如何使用管道在父级和子级之间进行通信的基本概述。您的进程应该由系统委托(delegate)并行运行。
关于mysql - C语言每分钟计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31222961/