简体   繁体   English

是否会在不关闭工作的情况下重新读取/ proc中正在更新的文件?

[英]Will re-reading a file being updated in /proc without closing work?

I am re-reading the /proc/stat file to get the updated values. 我正在重新读取/proc/stat文件以获取更新的值。 First I opened the file, read each line, closed the file and re-opened to get the updated values. 首先,我打开文件,读取每一行,关闭文件,然后重新打开以获取更新的值。 I want to know if closing a file is necessary or I can achieve the same effect by seeking to starting of the file. 我想知道是否需要关闭文件,或者可以通过尝试启动文件来达到相同的效果。 I wrote a code which did not close the file, instead placed the file pointer to the beginning of the file, which worked as before. 我编写了一个代码,该代码没有关闭文件,而是将文件指针放置到文件的开头,该方法与以前一样工作。 But I wanted to know that will seeking to the starting of the file gurantee that I will get the updated information? 但是我想知道那将确保我将获取更新的信息到文件启动吗?

Edit: Another point, I am sleeping between the seeks and reads. 编辑:另一点,我在寻求和阅读之间睡觉。

Although this question is not language specific here are the implementation languages in context: C, Perl. 尽管此问题不是特定于语言的,但这里是上下文中的实现语言:C,Perl。

EDIT 编辑

Here is the code I wrote. 这是我写的代码。

while ()
{
  open (STAT, "/proc/stat") or die "Cannot open /proc/stat\n";
  while (<STAT>)
  {
    #Stuff here
  }
  close (STAT);
  sleep 1;
}

Vs. VS.

open (STAT, "/proc/stat") or die "Cannot open /proc/stat\n";
while ()
{
  seek STAT, SEEK_SET, 0;
  while (<STAT>)
  {
    #Stuff here
  }
  sleep 1;
}
close (STAT);

Which one is preferable? 哪一个更好?

Both of those should work. 这两个都应该起作用。 seek should clear the EOF flag on your filehandle so you can read it a second time, but if you need to be absolutely sure you're getting a fresh copy, I would go with closing and re-opening. seek 应该清除文件句柄上的EOF标志,以便您可以再次阅读它,但是如果您需要绝对确定要获取新副本,则可以关闭并重新打开。

See seek for more information. 请参阅寻求更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM