简体   繁体   English

使用哪个命令在C ++代码[Linux]中执行程序?

[英]Which command to use to execute a program within C++ code [Linux]?

Greetings, 问候,

Am new to C++ and Linux. 是C ++和Linux的新手。 Am looking for a command that I use to execute 3 executable programs (exe/bin) in my source code, and this what i want to do: 我正在寻找一个用于在源代码中执行3个可执行程序(exe / bin)的命令,这就是我想做的:
1. Know if the process executed successfully (return value) 1.知道过程是否成功执行(返回值)
2. Know process ID 2.知道进程ID
3. Kill a process 3.终止进程

I tried System(), but it doesn't return on error and no PID, also not safe. 我尝试了System(),但是它不会返回错误且没有PID,也不安全。 I had a quick look at fork()-exec() but is it possible not to have parent-child relation? 我快速看了一下fork()-exec(),但是可能没有父子关系吗? Also, i looked into the man pages but i didn't understand :( 另外,我看了手册页,但我听不懂:(

Please, advice me on which command I shall use. 请给我建议我应该使用哪个命令。

Thank you in advance! 先感谢您!

Have you looked at popen()? 您看过popen()吗? This might be the way to go. 这可能是要走的路。 Try the man page. 尝试手册页。

system() does return the exit code of the child process the same way wait() does (or -1 on error, or 127 if it failed to spawn the shell process). system()确实以与wait()相同的方式返回子进程的退出代码(如果出错,则返回-1 ;如果未能生成shell进程,则返回127 )。

If you need to know the PID of the child and run it asynchronously, fork() followed by exec() is usually the way to go. 如果您需要知道子代的PID并异步运行它,通常可以使用fork()后跟exec() Use popen() instead if you want to communicate with the child process through a pipe. 如果要通过管道与子进程通信,请使用popen()代替。

To alleviate the inherent parent/child relationship, you'll probably have to daemonize the child process. 为了减轻固有的父子关系,您可能必须守护子进程。

By definition, you always have a parent-child relation when starting new programs (except when they replace your own program in the current process; you get that when calling execl without fork ing first). 根据定义,在启动新程序时,您始终具有父子关系(除非它们在当前进程中替换了您自己的程序;在不先fork情况下调用execl时,您会得到这种关系)。 Functions likes system and popen internally also call fork and one of the exec variants. 内部喜欢systempopen函数也调用forkexec变体之一。

Have a look at Fork and Exec tutorial from the University of Cambridge, it's pretty straight-forward and to the point. 看一下剑桥大学的Fork and Exec教程 ,这很简单直接。 Also uses C++. 也使用C ++。 Note that all the relevant calls ( fork , execl , wait ) are C POSIX functions. 请注意,所有相关调用( forkexeclwait )都是C POSIX函数。

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

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