gpt4 book ai didi

c++ - 在没有 shell 的情况下从 C++ 执行二进制文件

转载 作者:太空宇宙 更新时间:2023-11-04 15:35:30 24 4
gpt4 key购买 nike

有没有办法在没有 shell 的情况下从我的 C++ 程序执行二进制文件?每当我使用系统时,我的命令都会通过 shell 运行。

最佳答案

你需要:

  1. fork 进程
  2. 调用子进程中的“exec”函数之一
  3. (如有必要)等待它停止

例如,这个程序运行ls

#include <iostream>

#include <unistd.h>
#include <sys/wait.h>

// for example, let's "ls"
int ls(const char *dir) {
int pid, status;
// first we fork the process
if (pid = fork()) {
// pid != 0: this is the parent process (i.e. our process)
waitpid(pid, &status, 0); // wait for the child to exit
} else {
/* pid == 0: this is the child process. now let's load the
"ls" program into this process and run it */

const char executable[] = "/bin/ls";

// load it. there are more exec__ functions, try 'man 3 exec'
// execl takes the arguments as parameters. execv takes them as an array
// this is execl though, so:
// exec argv[0] argv[1] end
execl(executable, executable, dir, NULL);

/* exec does not return unless the program couldn't be started.
when the child process stops, the waitpid() above will return.
*/


}
return status; // this is the parent process again.
}


int main() {

std::cout << "ls'ing /" << std::endl;
std::cout << "returned: " << ls("/") << std::endl;

return 0;
}

输出是:

ls'ing /
bin dev home lib lib64 media opt root sbin srv tmp var
boot etc initrd.img lib32 lost+found mnt proc run selinux sys usr vmlinuz
returned: 0

关于c++ - 在没有 shell 的情况下从 C++ 执行二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35050381/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com