简体   繁体   English

如何在不使用system,popen,fork,exec的情况下在C / Linux中执行外部命令?

[英]How can I execute an external commands in C/Linux without using 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()? 我想知道是否有什么好方法可以在Linux环境下使用C语言在不使用system(),popen(),fork(),exec()的情况下执行外部命令?

The reason I cannot use these functions is that my main application has used up most of the system resources (ie 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. 从我读过的书中可以看到,system()和popen()实际上都在下面使用fork(),所以我也不能使用它们。

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. 我目前唯一的想法是在运行主应用程序并使用IPC(管道或套接字)之前创建一个进程,以使新进程知道使用system()或popen()运行它需要哪些外部命令并将结果返回完成后转到我的应用程序。

You cannot do this. 你不可以做这个。 Linux create new process by sequential call to fork() and exec() . Linux通过顺序调用fork()exec()来创建新进程。 No other way of process creation exists. 没有其他方法可以创建流程。

But fork() itself is quite efficient. 但是fork()本身非常有效。 It uses Copy-on-Write for child process, so fork() not copy memory until it is really needed. 它对子进程使用写时复制 ,因此fork()直到真正需要时才复制内存。 So, if you call exec() right after fork() your system won't eat too much memory. 因此,如果在fork()之后立即调用exec() ,则系统不会占用太多内存。

UPD. UPD。 I lie to you saying about process creation. 我骗你说关于流程创建。 In fact, there is clone() call which fork() uses internally. 实际上,存在fork()内部使用的clone()调用。 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. 阅读man 2 forkman 2 clone以获取更多信息。

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

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