(如果我术语有误,请纠正)所以我需要从文件描述符中读取,但是read方法需要一个整数来读取那么多字节的大小,或者我可以使用O_NONBLOCK,但我仍然必须设置一个未知大小的缓冲区大小。这使得它很困难。以下是我的代码:
这是处理所有轮询和mkfifo的方法,并且N已经在主函数中预定义了
struct pollfd pfd[N];
int i;
for(i = 0; i < N; i++)
{
char fileName[32];
snprintf (fileName, sizeof(fileName), "%d_%di", pid, i);
mkfifo(fileName, 0666);
pfd[i].fd = open(fileName, O_RDONLY | O_NDELAY);
pfd[i].events = POLLIN;
pfd[i].revents = 0;
snprintf (fileName, sizeof(fileName), "%d_%do", pid, i);
mkfifo(fileName, 0666);
i++;
pfd[i].fd = open(fileName, O_WRONLY | O_NDELAY);
pfd[i].events = POLLOUT;
pfd[i].revents = 0;
i--;
}
while(1)
{
int len, n;
n = poll(pfd, N, 2000);
if( n < 0 )
{
printf("ERROR on poll");
continue;
}
if(n == 0)
{
printf("waiting....\n");
continue;
}
for(i = 0; i < N; i++)
{
char buff[1024]; <---i dont want to do this
if (pfd[i].revents & POLLIN)
{
printf("Processing input....\n");
read(pfd[i].fd, buff, O_NONBLOCK);
readBattlefield(buff);
print_battleField_stats();
pfd[i].fd = 0;
}
}
}
我还看到一篇文章说,一旦read()读取所有的数据,它就会清空管道,这意味着我可以再次使用同一个管道来处理其他传入的数据。但是它并不清空管道,因为我无法再次使用同一个管道。我向我的教授提问,但他只是建议使用类似scanf的函数,但如果scanf需要一个文件流,而poll.fd是一个整数,那么我应该如何使用scanf呢?我的最终问题是,如何通过文件描述符使用scanf或其他方法读取传入的数据?使用scanf将更有助于我处理数据。
编辑:在另一个终端中,我必须输入cat file > (named_file),然后我的主程序将读取输入数据,以下是输入数据的样式:
3 3
1 2 0
0 2 0
3 0 0
前两个数字是网格信息和玩家数量,之后是网格内容,但这只是简化版本,我将处理超过100个玩家和超过1000个网格的情况。
i++
和i--
看起来不对。 - keltar