[英]What is a good and optimized way to run shell command in a pthread?
Basically, I want to compress a file in a pthread thread using gzip. 基本上,我想使用gzip在pthread线程中压缩文件。 The first solution that pops up in mind and on Google is to call system().
在Google上出现的第一个解决方案是调用system()。
What does the stackoverflow community suggest? stackoverflow社区建议什么?
Shall I use system() in a pthread? 我应该在pthread中使用system()吗?
Or shall I myself just fork and exec in pthread? 还是我自己只是在pthread中执行并执行? But since pthread is a thread, is it advisable to do a fork() and exec() in pthread thread?
但是由于pthread是线程,是否建议在pthread线程中进行fork()和exec()?
Or what is the better approach than the above? 还是比上面更好的方法?
Start with system
call in another thread and only add complexity when needed. 从另一个线程中的
system
调用开始,仅在需要时才增加复杂性。
The extra complexity of doing fork
/ exec
or using a zip
library is only worth the effort if system
is not sufficient for some reason (ie you want to redirect both stdin
and stdout
of the child process into your parent process, or your want to compress a file in memory for sending it over the network without writing new files). 仅当
system
由于某些原因不够用时(例如,您要将子进程的stdin
和stdout
都重定向到父进程中,或者想要压缩),执行fork
/ exec
或使用zip
库的额外复杂性才值得付出努力。内存中的文件,无需编写新文件即可通过网络发送该文件)。
You shouldn't use system
for this, but not because it's expensive. 您不应该为此使用
system
,但不要因为它昂贵。 (For any file that is worth bothering to compress, the overhead of any technique for invoking a background gzip compression is negligible relative to the cost of doing the compression itself.) The reason you shouldn't use system
is, system
invokes a shell, and that means you have to worry about quoting the arguments. (对于任何值得压缩的文件,调用后台gzip压缩的任何技术的开销相对于执行压缩本身的成本而言都是微不足道的。)不应使用
system
的原因是, system
调用shell,这意味着您必须担心引用参数。 If you use fork
and execvp
instead, you don't have to worry about quoting anything. 如果改用
fork
和execvp
,则不必担心引用任何内容。
The problems associated with mixing fork
and wait
with threads are real, but they are tractable. 与混合
fork
和wait
线程相关的问题是真实的,但它们很容易解决。 If your OS has posix_spawn
, it will take care of some of those problems for you. 如果您的操作系统具有
posix_spawn
,它将为您解决其中的一些问题。 I don't normally recommend posix_spawn
because code that uses it is, in general, harder to maintain than code that uses fork
, but for this application it should be OK. 我通常不推荐
posix_spawn
因为使用它的代码通常比使用fork
代码更难维护,但是对于此应用程序来说应该可以。 I cannot fit a comprehensive guide to mixing fork
and wait
with threads into this answer box. 我无法提供综合指南来混合
fork
并wait
线程进入此答案框。
An alternative you should consider is compressing the data in the thread that would be waiting for the gzip
process, using zlib . 您应该考虑的替代方法是使用zlib在等待
gzip
进程的线程中压缩数据。 This avoids the problems of mixing fork
and wait
with threads, but it adds a library dependency to your program, which may not be as convenient as relying on an external gzip
executable. 这避免了混合的问题,
fork
,并wait
与线程,但它增加了一个库依赖于你的程序,这可能不一样便利依赖于外部gzip
可执行文件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.