问题描述
在 fork()
中创建活动子进程后,我在弄清楚如何使用它们时遇到问题。我从另一个终端看到它们仍然处于活动状态,直到我执行退出成功为止。例如,如果我想说:我想让 pid 为 10243 的子进程当前处于活动状态,请执行此方法。我想在所有孩子都初始化之后调用该方法,所以在 fork 之后。我必须输入 execvp ()
吗?
execvp (methodName (a))
?
所以假设我做了一个循环,我创建了 n 个孩子
switch (pid = fork()) {
case -1:
/* Handle error */
fprintf(stderr,"%s,%d: Errore (%d) nella fork\n",__FILE__,__LINE__,errno);
exit(EXIT_FAILURE);
case 0:
//here I have saved the pid of the child process
break;
default:
/* PARENT CODE: nothing here */
wait(NULL);
exit(0);
break;
}
}```
So at that point I have created n number of child process. Now I want,for example,that the child with the pid 10342 do a method called "method1()",and the child with the pid 10343 do a method called "method2()".
How can I say that? Is that possibile? Because I need first to create all the child and then use them while the "main process" is in stand by with an infinte cycle. Like:
```int u = 0;
while(u == 0){ I will handle the end of this with a signal
}
}
exit(EXIT_SUCCESS);
解决方法
来自 fork 的手册页:
子进程和父进程在不同的内存空间中运行。在 fork() 时,两个内存空间的内容相同。
也就是说,内存中的所有函数都可以被父进程和子进程调用,但是没有办法,一个进程可以调用驻留在另一个进程内存空间中的函数。
为此,您需要 IPC(进程间通信)。
附录:
在 fork 之后,您可以运行您喜欢的每个函数(在子进程中 - 我希望您知道这意味着什么,如果没有,提供的链接将帮助您)。但是,只有通过 IPC 才能“激活”子进程并运行某个方法。