问题是:这个程序应该接收来自 stdin 的输入并计算插入的字节数; SIGUSR1 信号将停止主程序,并在文件标准错误上打印当我发送 SIGUSR1 时已复制了多少字节。
这就是我的老师希望我这样做的方式:在一个终端运行中
cat /dev/zero | ./cpinout | cat >/dev/null
而从第二个终端发送信号
kill -USR1 xxxx
其中 xxxx 是 cpinout 的 pid。
我更新了之前的代码:
/* cpinout.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>
#define BUF_SIZE 1024
volatile sig_atomic_t countbyte = 0;
volatile sig_atomic_t sigcount = 0;
/* my_handler: gestore di signal */
static void sighandler(int signum) {
if(sigcount != 0)
fprintf(stderr, "Interrupted after %d byte.\n", sigcount);
sigcount = countbyte;
}
int main(void) {
int c;
char buffer[BUF_SIZE];
struct sigaction action;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
action.sa_handler = sighandler;
if(sigaction(SIGUSR1, &action, NULL) == -1) {
fprintf(stderr, "sigusr: sigaction\n");
exit(1);
}
while( c=getc(stdin) != EOF ) {
countbyte++;
fputc(c, stdout);
}
return(0);
}
信号只能写volatile sig_atomic_t
根据 C89 的变量和POSIX 7 http://pubs.opengroup.org/onlinepubs/9699919799/functions/signal.html标准:
如果信号处理程序引用除 errno [Option End] 之外的任何具有静态存储持续时间的对象 [CX] [Option Start],而不是将值分配给声明为 volatile sig_atomic_t 的对象,则行为未定义
实现通常会提供更多功能,但我怀疑您是否提供了使用非易失性全局变量或 printf 的功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)