linux - 如何在不带任何参数的情况下使用 exec() ?

标签 linux kernel call system

我想通过 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/

相关文章:

java - 是否建议每次在运行 jps 之前格式化 namenode?

linux - 在 Puppet 中更改节点声明中的类变量

c - 使用 spi-bitbang 驱动程序

perl - 在Perl中使用无括号的子例程调用的原因是什么?

windows - 通过 Windows VS 分区上的虚拟机在 Linux 中进行编码

linux - 从管道读取数据并写入标准输出,中间有延迟。也必须处理二进制文件

linux - 英特尔伽利略将内核头文件添加到交叉编译工具链

c - 这段代码中的值 12800 将一个字符输出到串口是什么?

java - Java中的finalize()方法什么时候被调用?

javascript - 简单例子中call、apply、bind的比较