【发布时间】:2013-10-06 15:18:09
【问题描述】:
我正在编写的 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?
}
}
- 我是否对新进程进行了 fork 并检查它是否是正确的子进程
- 我可以在这里使用什么 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);
【问题讨论】:
-
在 Stackoverflow 上有很多类似的问题。