我写的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?
}
}
假设用户可能输入类似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);
答案 0 :(得分:49)
这是一个简单易读的解决方案:
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
以查看孩子退出的方式(成功,失败或带有信号)。