我有一个代码,我在其中运行系统 API 以在 while(1) 循环中检查另一个进程的 pid。循环中有 1 秒的睡眠。此外,我正在检查呼叫是否以这种方式每秒执行一次,
#include<stdio.h>
#include <time.h>
#include <unistd.h>
#include<stdlib.h>
#include<math.h>
#include<signal.h>
int main()
{
struct timespec now;
unsigned long long prev;
int diff = 0;
if( clock_gettime( CLOCK_REALTIME, &now) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}
prev = now.tv_sec;
while(1) {
int ret = system("/sbin/pidof vim > /dev/null");
if( clock_gettime( CLOCK_REALTIME, &now) == -1 ) {
perror( "clock gettime" );
exit( EXIT_FAILURE );
}
if(prev != 0 ) {
diff = abs(now.tv_sec - prev);
if( diff > 1)
printf("Diff %d prev = %lu now = %lu\n",diff,prev,now.tv_sec);
}
prev = now.tv_sec;
sleep(1);
}
return 0;
}
理想情况下,我希望根本看不到打印,但很多时候我看到 2 秒的差异。如果我评论 system() API,那么我看不到打印。我什至用计时选项运行了一个 strace,并且在看到问题时看不到任何时间增加。
是否存在 system() 卡住一段时间的已知问题?
样本输出
Diff 2 prev = 1640101799 now = 1640101801
Diff 2 prev = 1640101911 now = 1640101913