问题
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
回答1:
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.
回答2:
Try:
unzip /usr/bin/Folder.gz &
wait $!
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 using system
or some equivalent to run unzip, it should block until the command completes.
回答3:
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.
unzip /usr/bin/Folder.gz > output.txt
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.
回答4:
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
来源:https://stackoverflow.com/questions/6983233/waiting-for-unzip-to-finish-before-carrying-on-c-code-on-a-redhat-machine