c - 如何在c中使用子进程
问题描述
在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 才能“使”子进程处于活动状态并运行某种方法。
推荐阅读
- c# - TLS 致命:握手失败
- react-native - 在 react-native-video 中播放 youtube 视频
- ios - 无法使用 Xcode 10.2+ 构建的通用(胖)框架编译模拟器构建
- python-3.x - 使用python同时在多个文件上运行一个函数
- python - 如何为python安装解析器库
- grails - 如何在 grails 2 中使用拦截器?
- python - 用于pgp解密的lambda函数不起作用
- ruby-on-rails - 有没有办法通过使用 Ransack 左连接后添加的列进行搜索?
- python - Python Socket 如何在线程中使用recv获取连续的数据流?
- go - 为什么用两种方式转换相同的值,结果却不同?