使用fork、execvp执行UNIX命令

Executing UNIX commands using fork,execvp

本文关键字:UNIX 命令 执行 execvp fork 使用      更新时间:2023-10-16

我正在尝试创建一个程序,该程序接受包含UNIX命令列表的输入文件,并以特定顺序执行这些命令。我正在学习fork(), wait(), execvp()系统调用,对等待和分叉模式有一些疑问。这是我用来执行进程的结构。进程可以并行或顺序执行。我会在排序中决定这个。假设我必须按照A、B、C、D、e的顺序执行进程

这是我为此想出的结构。请让我知道这是否正确。

ExecuteNodes function()
For loop {}from 0 to vector size // vector - this is the data structure that will have all the input file details 
{
         For loop {}// this is for my ordering logic. For all nodes I calculate the number of      nodes     that can execute paralley . Also using this loop to set the nodes ready for execution
         For loop {
           if that node is ready for execution.
              run a loop for the number of concurrent processes for that node .
              pid = fork()
              if(pid == 0)
              execvp(); 
         }
}
for loop {all nodes}
{
    wait()
} 

这个结构正确吗?请告诉我您的建议/意见。

...
if( pid == 0 )
  execvp();
else if ( pid == -1 )
  // handle errors
...

您建议的结构不允许顺序执行,因为您没有调用wait直到所有节点执行完毕。你可以使用wait()的一个变体,它允许WNOHANG选项在不阻塞的情况下检查子进程的终止。

当你调用fork()时,你需要检查-1是否表示有错误,以及检查0是否表示调用已经在子进程中返回。

很难确切地知道应该建议什么结构,因为我不确定您需要什么顺序约束。