我正在编写的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);