简体   繁体   English

C中的popen()和system()有什么区别

[英]what is the difference between popen() and system() in C

I want to execute a binary within my C code. 我想在我的C代码中执行二进制文件。 Which is better to execute with? 执行哪个更好? popen() or system() popen()system()

EDIT : I tried to use system , but the process executing seems to get stuck in the end and does not return to my code. 编辑 :我试图使用system ,但执行过程似乎卡在最后,并没有返回到我的代码。

Any suggestions on what to do? 有关该怎么办的任何建议?

Thanks 谢谢

popen() gives you control over the process's input or output file streams. popen()使您可以控制进程的输入或输出文件流。 system() doesn't. system()没有。 If you don't need to access the process's I/O, you can use system() for simplicity. 如果您不需要访问进程的I / O,则可以使用system()来简化操作。

system() is in C89 and C99; system()在C89和C99中; popen() is Posix only (though the Windows API also has one). popen()只是Posix(虽然Windows API也有一个)。

Both functions invoke some form of a shell to execute the command (eg /bin/sh on Linux, and probably cmd.exe on Windows). 这两个函数都调用某种形式的shell来执行命令(例如Linux上的/bin/sh ,以及Windows上的cmd.exe )。 If you want to execute an executable file directly and you are on Posix, you can also look at the exec* -family of functions in conjuction with fork() (since exec() replaces the current process). 如果你想直接执行一个可执行文件并且你在Posix上,你也可以使用fork()查看exec* -family函数(因为exec() 取代了当前进程)。

Use popen if you want to run a shell command and want the parent process to be able to talk to the child. 如果要运行shell命令并希望父进程能够与子进程通信,请使用popen (It hooks the child's input or output up to the stream you get back.) Otherwise, prefer the exec family of functions (likely in conjunction with fork ); (它将孩子的输入或输出挂钩到你得到的流。)否则,更喜欢exec系列函数(可能与fork一起); exec 'd processes inherit most open file descriptors (including stdin, stdout, and stderr), so you can hook input and output up to whatever you like...plus, there are fewer security implications. exec进程继承了大多数打开的文件描述符(包括stdin,stdout和stderr),因此你可以将输入输出挂钩到你喜欢的任何东西......而且,安全隐患更少。

system is generally best avoided unless you have to run shell commands. 除非必须运行shell命令,否则通常最好避免使用system It spawns a shell to run the command, and the shell can parse the command any way it likes. 它产生一个shell来运行命令,shell可以以任何方式解析命令。 In particular, certain environment variables (like $IFS and/or $PATH ) can be modified in such a way as to cause the parent to execute programs you never intended it to. 特别是,可以修改某些环境变量(如$IFS和/或$PATH ),以使父进程执行您从未想过的程序。 Although popen appears to do the same thing, it at least provides functionality that makes it worthwhile in the general case. 尽管popen看起来做同样的事情,但它至少提供了在一般情况下值得的功能。

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

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