[問題] 很詭異的現象...= =
繼剛剛問有好心大大 幫我解了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
12/20 17:28, 1F
→
12/20 17:32, , 2F
12/20 17:32, 2F
→
12/20 17:34, , 3F
12/20 17:34, 3F
推
12/21 00:43, , 4F
12/21 00:43, 4F
推
12/21 17:41, , 5F
12/21 17:41, 5F
→
12/21 21:04, , 6F
12/21 21:04, 6F
→
12/21 21:05, , 7F
12/21 21:05, 7F
→
12/21 21:13, , 8F
12/21 21:13, 8F
LinuxDev 近期熱門文章
PTT數位生活區 即時熱門文章