关于构建shell时的fork()

About fork() while building a shell

本文关键字:shell 时的 fork 构建 于构建      更新时间:2023-10-16

这是我的代码。

pid_t fpid=fork();
if(fpid > 0){
    wait(&fpid);
}
else{
    do_command();
}

问题是,函数do_command()只执行一行,所以我更改了do_command:

else{
    execlp("/bin/ls","ls","-al",NULL);
    cout<<"ntest<<endl;
}

此外,ls命令已执行,但cout命令丢失。。

我的代码出了什么问题?

请原谅我英语不好,帮帮我。

这是我的do_command()函数声明:

void do_command(const char *command) {
    //all commands with arguments

    const char *kernel_address = "/bin/";
    char *kernel_command;
    strcpy(kernel_command, kernel_address);
    strcat(kernel_command, command);
    cout << "nCommand is:" << kernel_command << "n" << endl;
    execlp(kernel_command, command, NULL);

}

此外,在子进程中调用函数时没有任何输出

下一行不会打印,因为exec系列命令只在出现错误时返回。如果没有错误,它将替换您的程序,并执行要在exec中执行的任何命令。因此,cout不工作

来自execlp:的手册

exec()函数族用新的进程映像替换当前进程映像。

一旦调用了execlp,程序就不再运行。它已被ls取代。因此,它永远不会到达cout