简体   繁体   English

Linux C进程等到文件副本完成(shell命令)

[英]Linux C process wait till copy of files completed (shell command)

I am trying to copy multiple folders and files from one folder (linux SBC) to another folder (USB mounted folder) from a process. 我试图从一个进程中将多个文件夹和文件从一个文件夹(Linux SBC)复制到另一个文件夹(USB挂载文件夹)。

My process is completely written in C. The linux system is an SBC running YOCTO, and it doesnt have rsync available. 我的进程完全用C编写.linux系统是一个运行YOCTO的SBC,它没有rsync可用。

I used popen command for most of the commands like mount , umount , etc.. But for copying ( cp command) I am not sure how to wait for the copy to complete. 我使用popen命令执行大多数命令,如mountumount等。但是对于复制( cp命令),我不知道如何等待副本完成。

I am using below format in my C code and it works (copying works) 我在我的C代码中使用以下格式并且它可以工作(复制工作)

system("yes | cp -rf " USB_DATA_SOURCE_PATH " " USB_DATA_DESTINATION_PATH);

I need to copy multiple files and there can be any number of files with dynamic names. 我需要复制多个文件,并且可以有任意数量的具有动态名称的文件。 All I need is a way to know that the copying is completed and is safe to umount and indicate to the user. 我只需要知道复制完成并且可以安全umount并向用户指示。

As hinted in the comments: 正如评论中暗示的那样:

  1. system() waits until cp has finished, so you don't have to add any wait cycles. system()等到cp结束,因此您不必添加任何等待周期。
  2. But when cp returns the copied data may not necessarily have already been written to disk from the buffers. 但是cp返回时,复制的数据可能不一定已经从缓冲区写入磁盘。 You can call sync explicitly to make this happen. 您可以显式调用sync来实现此目的。
  3. But umount already ensures the cache being synced/buffers flushed; 但是 umount已经确保缓存被同步/缓冲刷新; that's why it sometimes takes some time until umount returns. 这就是为什么它有时需要一些时间直到umount返回。

To wrap it all up, no need for an explicit sync between cp and umount , except if there are additional actions between and you want to make sure the data is synced even when the USB disk is yanked from the machine without being properly unmounted. 要将它全部包装起来,不需要在cpumount之间进行显式sync ,除非之间还有其他操作,并且您希望确保即使在未正确卸载USB磁盘的情况下从机器中取出数据也会同步数据。 In that case your best option is to extend your system() call: 在这种情况下,您最好的选择是扩展您的system()调用:

system("yes | cp -rf " USB_DATA_SOURCE_PATH " " USB_DATA_DESTINATION_PATH "; sync");

to force sync independent of the success of the copy command, or 强制sync独立于复制命令的成功,或

system("yes | cp -rf " USB_DATA_SOURCE_PATH " " USB_DATA_DESTINATION_PATH " && sync");

if you need to get the unchanged exit code of cp in case it fails. 如果你需要获取cp未更改退出代码,以防它失败。

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

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