分叉和执行许多不同的过程,并从每个过程中获取结果 [英] fork and exec many different processes, and obtain results from each one
问题描述
我设法从应用程序中派生并执行了一个不同的程序.我目前正在研究如何等待exec调用的过程通过管道或stdout返回结果.但是,我可以使用单个fork来处理一组进程吗?还是必须多次进行fork并再次调用同一程序?我可以为每个不同的过程获取PID吗?我希望我的应用程序调用我当前正在多次调用的同一程序,但参数不同:我希望一组8个进程运行同一程序,并通过管道返回结果.有人可以给我指出正确的方向吗?我已经阅读了linux.die手册页,但是它们的描述相当简明扼要.我可以找到电子书或pdf以获得详细信息吗?谢谢!
I have managed to fork and exec a different program from within my app. I'm currently working on how to wait until the process called from exec returns a result through a pipe or stdout. However, can I have a group of processes using a single fork, or do I have to fork many times and call the same program again? Can I get a PID for each different process ? I want my app to call the same program I'm currently calling many times but with different parameters: I want a group of 8 processes of the same program running and returning results via pipes. Can someone please point me to the right direction please ? I've gone through the linux.die man pages, but they are quite spartan and cryptic in their description. Is there an ebook or pdf I can find for detailed information ? Thank you!
pid_t pID = fork();
if (pID == 0){
int proc = execl(BOLDAGENT,BOLDAGENT,"-u","2","-c","walkevo.xml",NULL);
std::cout << strerror(errno) << std::endl;
}
例如,如何通过PID控制哪个子项(根据参数xml文件)获得了哪个结果(通过管道或stdout),并因此采取相应措施?我是否必须将子进程封装在一个对象中并从该对象开始工作,还是可以将它们完全分组?
For example, how can I control by PID which child (according to the parameter xml file) has obtained which result (by pipe or stdout), and thus act accordingly? Do I have to encapsulate children processes in an object, and work from there, or can I group them altogether?
推荐答案
一个Fork
syscall仅创建一个新进程(一个PID).您应该组织一些数据结构(例如,pids数组,管道的父级末端数组等),从主程序执行8 fork(每个孩子都会做exec
),然后等待孩子.
One Fork
syscall make only one new process (one PID). You should organize some data structures (e.g. array of pids, array of parent's ends of pipes, etc), do 8 fork from main program (every child will do exec
) and then wait for childs.
在每个fork()之后,它将返回您的孩子的PID.您可以存储以下pid和相关信息:
After each fork() it will return you a PID of child. You can store this pid and associated information like this:
#define MAX_CHILD=8
pid_t pids[MAX_CHILD];
int pipe_fd[MAX_CHILD];
for(int child=0;child<MAX_CHILD;child++) {
int pipe[2];
/* create a pipe; save one of pipe fd to the pipe_fd[child] */
int ret;
ret = fork();
if(ret) { /* parent */
/* close alien half of pipe */
pids[child] = ret; /* save the pid */
} else { /* child */
/* close alien half of pipe */
/* We are child #child, exec needed program */
exec(...);
/* here can be no more code in the child, as `exec` will not return if there is no error! */
}
}
/* there you can do a `select` to wait data from several pipes; select will give you number of fd with data waiting, you can find a pid from two arrays */
这篇关于分叉和执行许多不同的过程,并从每个过程中获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!