问题描述
我正在写的外壳需要执行由用户给它一个程序。这里是我的方案很缩短简化版本
INT的main()
{
将为pid_t PID = GETPID(); //这是父母的PID 字符* USER_INPUT = NULL;
为size_t line_sz = 0;
ssize_t供line_ct = 0; line_ct =函数getline(安培; USER_INPUT,&安培; line_sz,标准输入); //所以得到用户的输入,在店内USER_INPUT 为(;;)
{
将为pid_t child_pid = fork()的; //叉重复过程 将为pid_t child_ppid = getppid(); //获取孩子的父母PID 如果(child_ppid == PID)//如果当前过程是主进程的子
{
EXEC(); //这里我需要执行任何程序是给USER_INPUT
出口(1); //确保避免fork炸弹
} 等待(); //所以如果这是我们需要等待子进程结束,对父进程? }
}
- 我有分叉的新工艺和放大器;检查,看看它的一个子进程正确
- 什么EXEC我可以使用这里我想要做什么?什么是最简单的方法
- 什么是我的论点等待?我看的文档是没有帮助太多
假设用户可能输入像LS,PS,PWD
感谢。
编辑:
为const char *持有的strdup =(input_line);
的char * argv的[2];的argv [0] = input_line;
的argv [1] = NULL;的char * envp [1];
envp [0] = NULL;execve的(保持,ARGV,envp);
下面是一个简单的,可读的解决方案:
将为pid_t父= GETPID();
将为pid_t PID =叉();如果(PID == -1)
{
//错误,未能到餐桌()
}
否则如果(PID大于0)
{
INT状态;
waitpid函数(PID,和放大器;状态,0);
}
其他
{
//我们的孩子
的execve(...);
_exit(EXIT_FAILURE); // EXEC永远不会返回
}
孩子可以使用储值父
如果需要知道父母的PID(尽管我在这个例子中没有)。家长只需等待孩子完成。有效地,孩子跑同步母体内,并且没有并行性。家长可以查询状态
在孩子退出何种方式看(成功,失败,或与信号)。
The shell i'm writing needs to execute a program given to it by the user. Here's the very shortened simplified version of my program
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?
}
}
- Have I forked the new process & checked to see if it's a child process correctly
- What exec could I use here for what I'm trying to do? What is the most simple way
- What are my arguments to wait? the documentation I'm looking at isn't helping much
Assume the user might input something like 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);
Here's a simple, readable solution:
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
}
The child can use the stored value parent
if it needs to know the parent's PID (though I don't in this example). The parent simply waits for the child to finish. Effectively, the child runs "synchronously" inside the parent, and there is no parallelism. The parent can query status
to see in what manner the child exited (successfully, unsuccessfully, or with a signal).
这篇关于如何正确使用叉子,EXEC,等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!