我想通过 exec() 运行“ls”命令,我的代码是 exec("/bin/ls", NULL) 但我收到一条文本显示“通过 exec 系统调用传递了 NULL argv[0] ”。如果我添加“all”作为参数,它就可以了。 exec("/bin/ls","全部",NULL)
但是,当我使用 exec("/bin/ps", NULL) 时,它可以正常工作。那么你能帮我找出我的程序出了什么问题吗?
顺便说一句:我使用 execl()
#include <iostream>
#include <unistd.h> //required for fork()
#include <sys/types.h> //required for wait()
#include <sys/wait.h> //required for wait()
using namespace std;
int main(){
string cmd="";
string cmdpath="/bin/";
cout<<endl<<getcwd(NULL,0)<<" >> ";
cin>>cmd;
cout<<endl;
string cmdCmdpath = cmdpath+cmd;
const char* charcmd = cmdCmdpath.c_str();
int x = fork();
if(x!=0){
cout<<"The command "<<cmd<<" is running"<<endl;
wait(NULL);
cout<<"Im parent!"<<endl;
}else if (x==0){
cout<<"Im child!"<<endl;
execl(charcmd,NULL);
cout<<"Child done"<<endl;
}
}
最佳答案
仔细阅读execl的描述:
The first argument, by convention, should point to the filename associated with the file being executed.
这意味着,第二个 execl
参数应该是路径,引用与第一个参数相同的文件。通常,第一个和第二个参数是相同的:
execl(charcmd, charcmd, NULL);
关于linux - 如何在不带任何参数的情况下使用 exec() ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32853926/