gpt4 book ai didi

c - getutent 和 Linux 计时器问题

转载 作者:太空狗 更新时间:2023-10-29 11:28:18 25 4
gpt4 key购买 nike

我在运行以下代码时遇到问题,该代码调用 getutent() 来计算当前登录到系统的用户总数。计时器将每 1 秒调用一次,并将名为“isSigAlrmOccured”的 bool 值设置为真并退出。主要功能通过检查此 bool 值来检查计时器信号是否已传递,并监视登录用户的数量。不幸的是,定时器信号只正确地传递给主程序两次,之后我没有收到任何进一步的信号。暂停函数调用在前两个信号后不会被中断。

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <utmp.h>
#include <errno.h>

static int isSigAlrmOccured;

void alarm_handler (int signo)
{
static int i=1;
printf("\n Signal Occurred %d times\n",i++);
isSigAlrmOccured = 1;

}

int main (int argc, char *argv[]) {
struct itimerval delay;
struct utmp *utmpstruct;
int numuser;


int ret;
signal (SIGALRM, alarm_handler);
delay.it_value.tv_sec = 1;
delay.it_value.tv_usec = 0;
delay.it_interval.tv_sec = 1;
delay.it_interval.tv_usec = 0;
ret = setitimer (ITIMER_REAL, &delay, NULL);
if (ret) {
perror ("setitimer");
return 0;
}
for (;;) {
pause ( );
/* count the number of users */
if ( (errno == EINTR) && (isSigAlrmOccured) ) {
isSigAlrmOccured = 0;
setutent();
while ((utmpstruct = getutent())) {
if ((utmpstruct->ut_type == USER_PROCESS) &&
(utmpstruct->ut_name[0] != '\0'))
numuser++;
}
endutent();
}
}
return 0;
}

输出:

信号出现1次

信号发生2次

最佳答案

*utent() 的实现正在使用 alarm() 并正在重置您的闹钟。
你必须做点别的事情。

strace ttest(为简洁起见删除了一些行)
[...]
暂停()
--- SIGALRM (闹钟) @ 0 (0) ---
write(1, "信号发生1次\n", 25 信号发生1次) = 25
打开("/var/run/utmp", O_RDONLY|O_CLOEXEC) = 3
闹钟(0) = 5
rt_sigaction(SIGALRM, {0x7f52580a91c0, [], SA_RESTORER, 0x7f5257fd46e0}, {0x40075c, [ALRM], SA_RESTORER|SA_RESTART, 0x7f5257fd46e0}, 8) = 0
警报(1)= 0

仅在 sleep 期间设置闹钟的示例代码。

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <utmp.h>
#include <errno.h>

static int isSigAlrmOccured;

void alarm_handler (int signo)
{
static int i=1;
printf("\n Signal Occurred %d times\n",i++);
isSigAlrmOccured = 1;

}

int main (int argc, char *argv[]) {
struct itimerval delay;
struct utmp *utmpstruct;
int numuser;
int ret;

for (;;) {
signal (SIGALRM, alarm_handler);
alarm(1); /* wake me later */
pause ( );
/* count the number of users */
if ( (errno == EINTR) && (isSigAlrmOccured) ) {
signal (SIGALRM, SIG_DFL);
isSigAlrmOccured = 0;
numuser = 0;
setutent();
while ((utmpstruct = getutent())) {
if ((utmpstruct->ut_type == USER_PROCESS) &&
(utmpstruct->ut_name[0] != '\0'))
numuser++;
}
endutent();
printf("found %d users\n", numuser);
}
}
return 0;
}

关于c - getutent 和 Linux 计时器问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1334149/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com