我正在编写的 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 之类的内容
Thanks.
Edit:
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
}
孩子可以使用储值parent
如果它需要知道父进程的 PID(尽管在本例中我不需要)。家长只需等待孩子完成即可。实际上,子进程在父进程内部“同步”运行,并且不存在并行性。家长可以查询status
查看孩子以何种方式退出(成功、不成功或发出信号)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)