等待解压完成后再进行 C++ RedHat 机器上的代码
我想在我的 Redhat 机器上解压一个压缩文件夹。
为此,我向 bash 脚本发送字符串;
"unzip /usr/bin/Folder.gz"
这解压缩文件夹没有问题,就像我得到一般
inflating folderA/folderB/fileX
等一样。
但是,我想将代码保存在解压缩命令中,等待解压缩完成。
我尝试过使用,
sleep(5)
但我不想使用它,只是希望它总是需要不到五秒的时间,尤其是对于非常小的压缩文件来说,这效率很低。
我在网上搜索过但无济于事......
所以我的问题是;在解压缩完成之前停止程序的可靠方法是什么?
操作系统:Redhat
编程语言:C++
IDE:Eclipse
I want to unzip a zipped folder on my Redhat machine.
To do this I send a bash script the string;
"unzip /usr/bin/Folder.gz"
This unzips the folder no problem, as in I get the general
inflating folderA/folderB/fileX
etc.
However, I want to hold the code at the unzip command, waiting until the unzipping is complete.
I have tried using
sleep(5)
but I don’t want to use this and just hope that it will always take less than five seconds especially this is would be inefficient for very small zipped files.
I have searched online but to no avail...
So my question is; what is a reliable way to stall a program until the unzipping is complete?
O/S: Redhat
Programming Language: C++
IDE: Eclipse
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如何运行 bash 脚本?
如果您使用
system()
API,它将启动程序,然后等待生成的进程结束。system()
system 是由另外 3 个系统调用组成的调用:execl()、wait() 和 fork()。 来源。How do you run the bash script?
If you use the
system()
API it will start the program and then wait until the spawned process ends.system()
system is a call that is made up of 3 other system calls: execl(), wait() and fork(). Source.Try:
这将导致 shell 等待最后一个进程完成。最后执行的命令的 pid 存储在
$!
中。不确定这与 C++ 有何关系,但如果您想从代码中执行相同的操作,可以使用
waitpid
函数。当然,如果您希望程序在
unzip
执行时阻塞,我对确切的问题是什么感到有点困惑。假设您使用system
或类似的东西来运行 unzip,它应该会阻塞,直到命令完成。Try:
That will cause the shell to wait on the completion of the last process. The pid of the last executed command is stored in
$!
.Not sure how this relates to C++, but if you want to do the same from code you can use the
waitpid
function.Of course, if you want your program to block while
unzip
executes I'm a little confused as to what the exact problem is. Assuming you're usingsystem
or some equivalent to run unzip, it should block until the command completes.我不太确定这是最好的方法,但它是可靠的。
现在,只需将命令发送到 bash,为什么不将输出发送到某个文件呢?
一旦找到 100% 或输出的最后一行应包含的内容,请定期从 C++ 代码中读取文件(假设 1 秒),然后继续执行代码。
I'm not really sure this is the best way, but it is reliable.
Now instead just sending the command to the bash why not send the output to some file.
Read the file in regular intervals from your C++ code (lets say 1 sec) once you find 100% or whatever the last line of the output should contain and then carry on with your code.
我不知道这是否会过度杀伤或效率低下,但您可以将解压缩过程移至另一个线程,并停止主线程,直到该线程完成处理
I don't know if this would be overkill or inefficent, but you could move the process of unzipping in to another thread, and halt your main thread until that thread is finished processing