1

I'm trying to create a TAR archive from my program and then opening the archive for further processing. I have a 2 second delay between calling system() and open(). So far, it works fine, but I'm not sure why the 2 second delay is necessary or if it's the correct solution.

Without the delay, I get error code 2 (ENOENT "No such file or directory") from the open() call. My first thought was the filesystem wasn't updating itself fast enough and open() couldn't find the file. But what if the system is really busy? Do I need a longer delay? Should I loop until open() succeeds instead of the delay? Is the problem something completely different?

UPDATE
The root filesystem is EXT2. /tmp is mounted in RAM using TMPFS. I'm using tar to create an archive, not extract contents of one. Essentially, my program is supposed to create an archive of some log files and send them over the network (that's why I open the archive after creating it).

int return_value = system("/bin/tar -czf /tmp/logs.tar.gz /var/log/mylogs.log* &> /dev/null");
// error checks on return_value as described here: http://linux.die.net/man/2/wait
if(return_value != 0) {
  return return_value;
}
//usleep(2000000);
return_value = open("/tmp/logs.tar.gz", O_RDONLY | O_LARGEFILE, 0);
// success or failure depending on whether there's a delay or not
4

3 回答 3

2

您甚至可以通过在程序中直接tar使用libtar来避免运行外部命令。


添加

你应该向我们展示你的程序。我很确定如果调用system只是通过提取某些文件tar,它在成功 system调用后可用,例如:

 int err = system("/bin/tar xf /tmp/foo.tar bar");
 int fd = -1;
 if (err == 0)
      fd = open("bar", O_RDONLY);
 // fd is available

在这段代码中没有理由等待几秒钟。您可能正在做更复杂的事情,或者您忘记测试结果system

于 2011-12-19T20:00:55.277 回答
1

这是我会尝试的:

  1. fork/exec tar 你自己,并让你的父母收集 tar-child。如果系统在文件系统中引入了竞争条件,那么控制子进程的创建/获取可能会有所帮助。

  2. touch一个空文件(fopen用于写入和close),然后tar进入新文件。

  3. 给出tar选择--verify;该文件必须存在才能被验证:)

于 2011-12-20T01:08:52.677 回答
1

您认为您正在使用“&>”重定向 tar 的输出,但实际上您是在后台运行它,因为 system() 恰好调用了一个不支持 &> 的 shell,因此将其解释为“&”后跟“ >”。延迟会导致您的程序等待足够长的时间以使 tar 完成。

修复方法是修改您的命令以使用您的 shell 支持的语法。在任何情况下,从 tar 抛出错误输出都可能是一个错误。

于 2011-12-20T19:12:46.057 回答