本文探討一個《Unix/Linux編程實踐教程》P219出現的bug,在Linux上bounce_async.c程式碼運行失敗。
Unix有兩個非同步輸入(asynchronous input)系統。
一種方法是當輸入就緒時發送訊號,另一個系統當輸入被讀入時發送訊號。UCB(BSD)中通過設定檔案描述塊(file descriptor)的O_ASYNC位來實現第一種方法。
第二種方法是POSIX標準,它調用aio_read。
實驗第一種方法時,我採用書中代碼,就是一個彈球程式,發現了其不能在鍵入"Q"正常退出
#include <stdio.h>#include <stdlib.h>#include <curses.h>#include <signal.h>#include <fcntl.h>#define MESSAGE "hello"#define BLANK" "int row=10;int col =0;int dir =1;int delay =200;int done =0;int main(){void on_alarm(int);void on_input(int);void enable_kbd_signals();sigset_t * set;set=(sigset_t*)malloc(sizeof(set));sigemptyset(set);sigaddset(set,SIGIO);sigprocmask(SIG_UNBLOCK, set, NULL);initscr();crmode();noecho();clear();enable_kbd_signals();signal(SIGIO,(on_input));enable_kbd_signals();signal(SIGALRM,on_alarm);set_ticker(delay);move(row,col);addstr(MESSAGE);while(!done){pause();}endwin();}void on_input(int signum){int c = getch();if(c=='Q'||c==EOF)done=1;else if(c==' ')dir=-dir;}void on_alarm(int signum){signal(SIGALRM,on_alarm);mvaddstr(row,col,BLANK);col+=dir;mvaddstr(row,col,MESSAGE);refresh();if(dir==-1&&col<=0)dir=1;else if(dir==1&&col+strlen(MESSAGE)>=COLS)dir=-1;}void enable_kbd_signals(){int fd_flags;fcntl(0,F_SETOWN,getpid());fd_flags=fcntl(0,F_GETFL);fcntl(0,F_SETFL,(fd_flags|O_ASYNC));}
遇到這個問題後,我很困惑,於是郵件問了作者Bruce Molay,沒想到他神速的回複了我的郵件!興奮異常!
下面我貼出的回複,這不算侵權吧,@Bruce Molay~
bmolay@gmail.com
Dear Scott,
Thank you for writing. The reason that 'Q' does not get you out of the program
is that on this version of Linux (and on most, I think)
the signal handler is called,
the 'Q' is read, the done variable is set but the program never returns from pause().
Which is silly as pause is supposed to block until a signal is handled.
One solution is to change the on_input() function to call endwin and exit if the input
is 'Q' or EOF.
if ( c == 'Q' || c == EOF ){
done = 1;
move(LINES-1,0);
endwin();
exit(0);
}
I checked it, and pause returns once, but never returns again. The signal
handlers are called and processed but pause does not return.
Try the aio one. that one works. I think async version is not supported
on Linux very well.
他的英文還是很好懂的。真是很大家風範,大家以後遇到問題也可以多聯絡作者,It is so cool!!
Linux和Unix有一定的區別,在學習Unix的過程中,我們經常使用Linux做實驗,我們需要注意其區別!