[問題] 很詭異的現象...= =

看板LinuxDev作者 (人生遊戲 戲遊人生)時間16年前 (2009/12/20 17:23), 編輯推噓3(305)
留言8則, 3人參與, 最新討論串1/1
繼剛剛問有好心大大 幫我解了gets之後 我寫了一個 讀取者鎖-寫入者鎖 的程式 程式碼如下(先說好 不是要幫我debug 這編譯有通過 只是在執行時gets的地方好像會跳掉): #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> #define SIZE 100 //Set the input buffer size = 100 int main(int fd) { char input[SIZE]; char c; struct flock fl; FILE *fin,*fout; int choose; printf("------------Menu------------\n"); printf("1.WL\n2.RL\n3.Unlock\n"); printf("Enter your choose: "); scanf("%d",&choose); fl.l_whence = SEEK_SET; fl.l_start = 0; fl.l_len = 0; //EOF fl.l_pid = getpid(); switch(choose){ case 1: fl.l_type = F_WRLCK; //write lock fout = fopen("file","w"); fd = fileno(fout); fcntl(fd, F_SETLKW, &fl); //write lock fd printf("Input the string: "); gets(input); fputs(input,fout); break; case 2: fl.l_type = F_RDLCK; //read lock fin = fopen("file","r"); fd = fileno(fin); fcntl(fd, F_SETLKW, &fl); //read lock fd printf("The string be read is: "); while((c = fgetc(fin)) != EOF) printf("%c",c); printf("\nWait for 5 seconds...\n"); sleep(5); break; default: fl.l_type = F_UNLCK; //unloock fd = fileno(fout); fout = fopen("file","w"); fcntl(fd, F_SETLKW, &fl); printf("Input the string: "); gets(input); fputs(input,fout); break; } fl.l_type = F_UNLCK; fcntl(fd, F_SETLK, &fl); //unlock fd return 0; } 執行時如下: $ ./proc.o file ------------Menu------------ 1.WL 2.RL 3.Unlock Enter your choose: 1 Input the string: $ 搞不懂為何會降子 上一篇的程式執行起來就沒有這問題 另外 如果將程式中的gets(input); 改成scanf("%s",input); 就沒有此問題 缺點是 不能輸入空白鍵 不然它只能讀到句子中的第一個單字 今天難得會上來問兩篇 謝謝回答 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 123.240.190.163 ※ 編輯: amu1661024 來自: 123.240.190.163 (12/20 17:25)

12/20 17:28, , 1F
也許是\n的問題?
12/20 17:28, 1F

12/20 17:32, , 2F
意思就是說我的gets再我按鍵盤之前就先讀到\n囉?
12/20 17:32, 2F

12/20 17:34, , 3F
不過我真的看不出程式中有什麼地方能讓他讀到\n
12/20 17:34, 3F

12/21 00:43, , 4F
scanf("%d%*c",&choose); 這樣咧?
12/21 00:43, 4F

12/21 17:41, , 5F
是 \n 的問題沒錯
12/21 17:41, 5F

12/21 21:04, , 6F
喔 我懂了 因為之前再按scanf時的enter被保留下來
12/21 21:04, 6F

12/21 21:05, , 7F
所以之後gets會先讀到\n
12/21 21:05, 7F

12/21 21:13, , 8F
再gets下面再用一次gets果然可以 謝謝樓上諸位大大
12/21 21:13, 8F
文章代碼(AID): #1BBUqMip (LinuxDev)
文章代碼(AID): #1BBUqMip (LinuxDev)