gpt4 book ai didi

c - 在 fork/execvp 控制不返回父级之后

转载 作者:太空宇宙 更新时间:2023-11-04 04:04:40 24 4
gpt4 key购买 nike

当我在下面运行我的代码并在提示符下输入“ls”时,它会在终端中运行 ls,但随后就停在那里,不再打印我的提示符。我如何获得返回父进程的控制权?

谢谢

#include <stdio.h>
#include <string.h>
#include <unistd.h>

int main(int argc, char* argv[]){
while(1){
print_the_prompt();
char user_text[100];
if( fgets(user_text, sizeof(user_text), stdin) != NULL ){
char* nl_char = strchr(user_text, '\n');
if( nl_char != NULL ){
*nl_char = '\0';
}
}

//printf("user_text = \"%s\"\n", user_text);

if( is_command_built_in(user_text) ){
//run built in command
}
else{
//run regular command
execute_new_command(user_text);
}
}

return 0;
}

void print_the_prompt(){
printf("!: ");
}

int is_command_built_in(char* command){
return 0;
}

void execute_new_command(char* command){
pid_t pID = fork();
if(pID == 0){
//is child
char* execv_arguments[] = { command, (char*)0 };
execvp(command, execv_arguments);
}
else{
//is parent
printf("im done");
}
}

最佳答案

答案可能是父进程在启动子进程后立即打印“im done”(记住这是一个单独的进程,因此是并行运行的),然后循环打印之前的提示 child 甚至开始列出文件。如果向后滚动,您可能会找到下一个提示。

要让父级等待子级完成,您必须使用 wait() 函数族之一。

关于c - 在 fork/execvp 控制不返回父级之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7577619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com