系统()或fork()/执行exec()? [英] to system() or fork()/exec()?

查看:120
本文介绍了系统()或fork()/执行exec()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有似乎是从C在UNIX上运行的外部可执行文件的两种常用方法,在

There appear to be two common ways of running an external executable from C in unix, the

system()

通话以及

pid = fork()
switch(pid)
//switch statement based on return value of pid, 
//one branch of which will include and exec() command

是否有任何理由preFER叉子/ EXEC对系统的情况下,他们在功能上等同(父进程儿童完成,不需要复杂的信息从孩子返回等待?)。

Is there any reason to prefer a fork/exec over system in the case where they are functionally equivalent (parent process waits for child to finish, no complex information is returned from child)?.

推荐答案

系统执行命令间preTER,即壳,其中(a)是比直接叉/ EXEC慢,(b)可表现不同在不同的系统和(c)是一个潜在的安全隐患,如果你通过它来自不受信任来源的字符串。此外,系统等待子进程退出,而你可能希望它与父进程同时运行。

system executes a command-interpreter, i.e. a shell, which (a) is slower than a direct fork/exec, (b) may behave differently on different systems and (c) is a potential security hazard if you pass it a string from an untrusted source. Also, system waits for the child process to exit, while you might want it to run concurrently with the parent process.

在一般的多,低层叉/ EXEC为您提供了更多控制权:之前,或在两个操作之间,您可能希望 CHDIR ,打开管道,关闭文件描述符,设置共享内存等。

More in general, the low-level fork/exec gives you additional control: before or in between the two operations, you might want to chdir, open pipes, close file descriptors, set up shared memory, etc.

(通过不同的系统,我的意思并不是Windows还是Unix的(与Windows甚至没有叉):我说的是Red Hat Linux的Ubuntu的对比,前者使用的Bash要执行的传递给系统,后者轻巧的POSIX兼容的shell)。

(By different systems, I don't mean Windows vs. Unix (as Windows doesn't even have fork): I'm talking Red Hat Linux vs. Ubuntu. The former uses Bash to execute what is passed to system, the latter a lightweight POSIX-compatible shell.)

这篇关于系统()或fork()/执行exec()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆