使用 execvp 执行我在数组中的命令
using execvp to execute commands that I have in an array
我有一个命令数组,我想执行这个数组中的每个命令,但我似乎无法让它工作,所以我有
childPid = fork();
for(int i =0;i < numOfCommands;i++)
{
if(childPid == 0)
{
execvp(commands[i], argv);
perror("exec failure");
exit(1);
}
else
{
wait(&child_status);
}
}
这是做什么的,它只执行我数组中的第一个命令但不会继续执行,我将如何继续?
如果我想要随机执行命令的顺序并且结果混合在一起怎么办,那么我必须使用 fork 吗?
如果要执行多个程序,无论如何都需要使用fork
。来自 man exec
:(强调)
The exec()
family of functions replaces the current process image with a new process image.
…
The exec()
functions return only if an error has occurred.
通过使用fork
,您创建了一个具有相同图像的新进程,您可以通过调用exec
替换子进程中的图像,而不会影响父进程,然后是免费的fork
和 exec
多次。
别忘了wait
for the child processes to terminate. Otherwise, when they die they will become zombies。上面链接的 wait
联机帮助页中有一个完整的示例。
我有一个命令数组,我想执行这个数组中的每个命令,但我似乎无法让它工作,所以我有
childPid = fork();
for(int i =0;i < numOfCommands;i++)
{
if(childPid == 0)
{
execvp(commands[i], argv);
perror("exec failure");
exit(1);
}
else
{
wait(&child_status);
}
}
这是做什么的,它只执行我数组中的第一个命令但不会继续执行,我将如何继续?
如果我想要随机执行命令的顺序并且结果混合在一起怎么办,那么我必须使用 fork 吗?
如果要执行多个程序,无论如何都需要使用fork
。来自 man exec
:(强调)
The
exec()
family of functions replaces the current process image with a new process image.…
The
exec()
functions return only if an error has occurred.
通过使用fork
,您创建了一个具有相同图像的新进程,您可以通过调用exec
替换子进程中的图像,而不会影响父进程,然后是免费的fork
和 exec
多次。
别忘了wait
for the child processes to terminate. Otherwise, when they die they will become zombies。上面链接的 wait
联机帮助页中有一个完整的示例。