Reputation: 69
I wanna run "ls" command by exec(), and my code is exec("/bin/ls", NULL) but I got an text shows "A NULL argv[0] was passed through an exec system call." If I add "all" as parameter it woks. exec("/bin/ls","all",NULL)
however, when I use exec("/bin/ps", NULL), it works properly. So could you help me to figure out whats wrong with my program?
BTW: I use 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;
}
}
Upvotes: 2
Views: 5012
Reputation: 65870
Carefully read desctiption of execl:
The first argument, by convention, should point to the filename associated with the file being executed.
It means, that second the execl
parameter should be path, referred to the same file as the first one. Usually, the first and second parameters are same:
execl(charcmd, charcmd, NULL);
Upvotes: 2