如何正确使用fork,exec,等待

我写的shell需要执行用户给它的程序。 这是我的程序的缩短版本

int main() { pid_t pid = getpid(); // this is the parents pid char *user_input = NULL; size_t line_sz = 0; ssize_t line_ct = 0; line_ct = getline(&user_input, &line_sz, stdin); //so get user input, store in user_input for (;;) { pid_t child_pid = fork(); //fork a duplicate process pid_t child_ppid = getppid(); //get the child's parent pid if (child_ppid == pid) //if the current process is a child of the main process { exec(); //here I need to execute whatever program was given to user_input exit(1); //making sure to avoid fork bomb } wait(); //so if it's the parent process we need to wait for the child process to finish, right? } } 
  1. 我是否已分叉新流程并检查是否正确处理了子流程
  2. 我可以在这里使用什么exec来做我想做的事情? 什么是最简单的方法
  3. 我等待的理由是什么? 我正在看的文档没有多大帮助

假设用户可能输入类似ls,ps,pwd的内容

谢谢。

编辑:

 const char* hold = strdup(input_line); char* argv[2]; argv[0] = input_line; argv[1] = NULL; char* envp[1]; envp[0] = NULL; execve(hold, argv, envp); 

这是一个简单易读的解决方案:

 pid_t parent = getpid(); pid_t pid = fork(); if (pid == -1) { // error, failed to fork() } else if (pid > 0) { int status; waitpid(pid, &status, 0); } else { // we are the child execve(...); _exit(EXIT_FAILURE); // exec never returns } 

如果需要知道父节点的PID,孩子可以使用存储值parent节点(虽然我不在这个例子中)。 父母只是等待孩子完成。 有效地,孩子在父母内部“同步”运行,并且没有并行性。 父母可以查询status以查看孩子退出的方式(成功,不成功或带有信号)。