我在c中完全是菜鸟.我必须编写一个mypause()应具有与pause()系统调用类似的功能的函数,并mypause()在重复阻止等待信号的程序中测试该函数.te pause()功能如何工作?我不能这样做mypause():
fprintf( stderr, "press any key to continue\n" );
Run Code Online (Sandbox Code Playgroud)
为了让程序阻止并等待信号?
请记住,我不能使用pause()或sigpause().
我有这个代码,我必须让程序块反复等待信号.我的老师希望我们使用sigsuspend和面具而不是暂停或睡眠.我不熟悉的sigsuspend或面罩,我知道,sigsuspend()临时替换用面膜给出的面具调用进程的信号屏蔽,然后挂起过程,直到传递的信号,其作用是调用信号处理程序或终止进程.但是我该如何实现呢.
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
unsigned Conta = 0;
void mypause(int sign)
{
switch (sign)
{
case SIGINT:
printf("You've pressed ctrl-C\n");
printf("I'm running waiting for a signal...\n");
Conta++;
break;
case SIGQUIT:
printf("You've pressd ctrl-\\n");
printf("Number of times you've pressed CTRL-C: %d", Conta);
exit(0);
break;
}
}
int main()
{
alarm(3);
printf("I'm Alive\n");
signal(SIGINT, mypause);
signal(SIGQUIT, mypause);
printf("I'm running, waiting for a signal...\n");
while (1)
{
}
return (0);
}
Run Code Online (Sandbox Code Playgroud) 我制作了这段代码,我必须使用闹钟信号(SIGALRM)让程序每隔3秒打印一条消息"我还活着".
但是它不起作用,只有当我按下CTR-C时才会发出"我活着"的消息,我猜我没有把SIGALRM功能放在正确的位置,你能帮助我吗?
#include <stdlib.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
unsigned Count = 0; //Counts the number of times it receives the signal SIGINT.
void mypause(int sign); //prototype of the function my pause.
void mypause(int sign) {
signal(SIGALRM, mypause); //Set alarm clock for 3 seconds.
alarm(3);
printf("I'm Alive");
signal(SIGINT, mypause);
switch (sign) {
case SIGINT:
printf("\nPressed CTR-C\n");
printf("I'm running, waiting for a sign\n");
Count++;
break;
case SIGQUIT:
printf("\nPressed CTR-\\n");
printf("You pressed CTR-C %d times", …Run Code Online (Sandbox Code Playgroud) c ×3