简体   繁体   English

使用fork,execvp执行UNIX命令

[英]Executing UNIX commands using fork,execvp

I am trying to create a program that takes in an input file containing a list of UNIX commands and executes these commands in a particular order. 我正在尝试创建一个程序,该程序采用包含UNIX命令列表的输入文件,并以特定顺序执行这些命令。 I am learning fork() , wait() , execvp() system calls and had some questions about the wait and forking pattern. 我正在学习fork()wait()execvp()系统调用,并且对wait和fork模式有一些疑问。 This is the structure I am using for executing processes. 这是我用于执行流程的结构。 Processes can execute in parallel or sequentially. 进程可以并行或顺序执行。 I will be deciding this in the ordering. 我将在订购时决定。 Say I have to execute processes in the order A, B, CD, E. 假设我必须按照A,B,CD,E的顺序执行流程。

Here is the structure I came up with for this. 这是我为此想到的结构。 Please let me know if this is correct. 请让我知道这是否正确。

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()
} 

Is this structure correct ? 这种结构正确吗? Please let me know your suggestions/comments. 请让我知道您的建议/意见。

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

The structure you propose does not allow for sequential execution, as you do not call wait until all nodes have been executed. 您建议的结构不允许顺序执行,因为在执行所有节点之前,您不会调用wait。 You can use one of the variants of wait() which allow the WNOHANG option to check for termination of a child without blocking. 您可以使用wait()的一种变体,该变体允许WNOHANG选项检查子项的终止而不会阻塞。

When you call fork() you need to check for -1 which indicates an error, as well as checking for 0 indicating the call has returned in the child process. 当您调用fork()时,您需要检查-1表示错误,以及检查0表示该调用已在子进程中返回。

It is difficult to know exactly what structure to suggest as I am not sure what sequential constraints you require. 由于我不确定您需要什么顺序约束,因此很难确切知道要建议的结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM