如何解决SIGACTION处理程序可在中断后重复加载
您的stackoverflow系列,
我正在做一个uni任务,以使linux程序读取密码并保护该密码,如果用户在此期间中断了密码,则再次“重新读取”该密码。
这是我捕获处理程序的代码。
void catch_suspend(int sig_num)
{
printf("\nSuspending execution...\n");
fflush(stdout);
echo_on(YES); // re-enable echo mode
raise(SIGSTOP); // stop self
// we'll get back here when the process is resumed
printf("Resuming execution...\n");
echo_on(NO); // disable echo mode again
printf("Password: "); // reproduce the prompt
fflush(stdout);
}
这是主程序
int main(int argc,char *argv[])
{
#define MAX_SIZE 30
char user[MAX_SIZE]; // user name supplied by the user
char passwd[MAX_SIZE]; // password supplied by the user
sigset_t sigs;
struct sigaction sa_new;
memset(&sa_new,sizeof(sa_new)); // initialization to zeros
sa_new.sa_handler = catch_suspend; // set handler
sigemptyset(&sa_new.sa_mask); // mask: empty set
sigaddset(&sa_new.sa_mask,SIGINT); // mask: add SIGINT
sigaddset(&sa_new.sa_mask,SIGQUIT); // mask: add SIGQUIT
sa_new.sa_flags = 0; // no flags
printf("Username: "); // prompt the user for a user name
fflush(stdout);
fgets(user,MAX_SIZE,stdin); // wait for input
sigaction(SIGTSTP,&sa_new,&sa_old); // set the handler for SIGTSTP and get old handler setting
printf("Password: "); // prompt the user for a password
fflush(stdout);
echo_on(NO); // set input to no-echo mode
fgets(passwd,stdin); // get the user input
echo_on(YES); // re-enable echo on input
printf("\n"); // the Enter pressed by the user was not echoed
fflush(stdout);
// verify the password (\n is stored,don't compare it)
etc...
return 0;
我还应该阻止除SIGINT和SIGQUIT以外的所有信号,不确定是否正确使用了掩码。我现在遇到的问题是:在读取密码期间中断之后,进程停止了。没关系。但是,在我使用“ fg”命令继续执行之后,我的处理程序仅写输出并且程序结束,但是我需要它再次运行 fgets(passwd,MAX_SIZE,stdin)(已停止)
我想我可能没有正确设置old_action,但是我阅读的手册并没有真正使我更清楚。谁能伸出援手?
解决方法
好的,我终于弄清楚了,我要把它留给有相同问题的任何人。
我没有如下设置sigaction标志:
sa_new.sa_flags = SA_RESTART;
此标志控制在某些原语(例如打开,读取或写入)期间传递信号时发生的情况,并且信号处理程序正常返回。有两种选择:库函数可以恢复,或者可以返回错误代码EINTR的失败。
对于发送的特定信号,该选择由SA_RESTART标志控制。如果设置了该标志,则从处理程序中返回将恢复库函数。如果清除该标志,则从处理程序返回会使函数失败
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。