如何使用没有任何参数的exec()?

时间:2015-09-29 21:17:19

标签: linux kernel call system

我想通过exec()运行“ls”命令,我的代码是exec(“/ bin / ls”,NULL)但我得到一个文本显示“A NULL argv [0]通过exec系统调用传递“。如果我添加“all”作为参数,它就会出现问题。 EXEC( “/ bin中/ LS”, “所有”,NULL)

但是,当我使用exec(“/ bin / ps”,NULL)时,它可以正常工作。那么你能帮我弄清楚我的程序有什么问题吗?

BTW:我使用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;
        }

}

1 个答案:

答案 0 :(得分:2)

仔细阅读execl的解释:

  

按照惯例,第一个参数应指向与正在执行的文件关联的文件名。

这意味着,execl参数应该是第二个路径,与第一个文件引用相同的文件。通常,第一个和第二个参数相同:

execl(charcmd, charcmd, NULL);