如何在不使用system,popen,fork,exec的情况下在C/Linux中执行外部命令? [英] How can I execute an external commands in C/Linux without using system, popen, fork, exec?

查看:355
本文介绍了如何在不使用system,popen,fork,exec的情况下在C/Linux中执行外部命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道在Linux环境中是否有使用C语言在不使用system(),popen(),fork(),exec()的情况下执行外部命令的好方法?

I would like to know if there is any good way to execute an external command in Linux environment using C language without using system(), popen(), fork(), exec()?

之所以不能使用这些功能,是因为我的主应用程序已经用完了嵌入式板上的大多数系统资源(即内存).如果我进行了分叉,则开发板将无法创建我的主应用程序的副本.从我读过的书中可以看到,system()和popen()实际上都在下面使用fork(),所以我也不能使用它们.

The reason I cannot use these functions is that my main application has used up most of the system resources (i.e memory) in my embedded board. If I do a fork, the board won't be able to create a duplicate of my main application. From I read in a book, both system() and popen() actually using fork() underneath, so I cannot use them either.

我目前唯一的想法是在运行主应用程序并使用IPC(管道或套接字)之前创建一个进程,以使新进程知道使用system()或popen()运行并返回所需的外部命令.完成后将结果返回给我的应用程序.

The only idea I currently have is create a process before I run my main application and use IPC(pipe or socket) to let the new process know what external commands it needs to run with system() or popen() and return the results back to my application when it is done.

推荐答案

您不能执行此操作. Linux通过顺序调用fork()exec()来创建新进程.没有其他方法可以创建流程.

You cannot do this. Linux create new process by sequential call to fork() and exec(). No other way of process creation exists.

但是fork()本身非常有效.它将写时复制用于子进程,因此fork()不进行复制直到真正需要它为止.因此,如果您在fork()之后立即调用exec(),则系统不会占用过多的内存.

But fork() itself is quite efficient. It uses Copy-on-Write for child process, so fork() not copy memory until it is really needed. So, if you call exec() right after fork() your system won't eat too much memory.

UPD.我骗你说关于流程创建.实际上,有fork()在内部使用的clone()调用.该调用提供了对流程创建的更多控制,但是使用起来可能很复杂.阅读man 2 forkman 2 clone了解更多信息.

UPD. I lie to you saying about process creation. In fact, there is clone() call which fork() uses internally. This call provides more control over process creation, but it can be complicated to use. Read man 2 fork and man 2 clone for more information.

这篇关于如何在不使用system,popen,fork,exec的情况下在C/Linux中执行外部命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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