我正在编写的 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?
}
}
- 我是否分叉了新进程并检查了它是否是正确的子进程
- 我可以在这里使用什么 exec 来做我想做的事情?最简单的方法是什么
- 我有什么理由等待?我正在查看的文档没有多大帮助
假设用户可能会输入类似 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);