c - 如何检查正在运行的进程?
问题描述
假设我使用 fork 两次来获取两个子进程。然后,我想根据正在运行的进程以不同的方式执行 3 个进程(包括父进程)。这将如何在 c 语言中完成?以下工作是否有效:假设 PID1 是孩子 1 的进程 ID,类似地 PID2 是孩子 2,然后:我首先使用以下方法创建了两个孩子:
pid1 = fork();
if(pid1 == 0){
PID1=getpid();
}
if(pid1 > 0){
pid2 = fork();
if(pid2 > 0){
printf("\nParent ProcessL %d\n",getpid());
}
else if(pid2 == 0){
PID2=getpid();
}
}
-----------------------------------------------------
further down in my code:
while(/*true for a certain time*/){
if (PID1==getpid()){
//execute the code for child 1
} else if (PID2==getpid()){
// execute code for child 2
} else {
// execute the code for the parent
}
顺便说一句,进程是随机运行还是按顺序运行(每个进程的时间固定)?
解决方案
不会因为孩子中的pid
返回值是.fork()
0
实现目标的最简单方法是在每个fork()
.
pit_t PID1, PID2;
if(0>(PID1=fork()) {/*handle error*/}
if(!PID1) _exit(code_for_child1());
if(0>(PID2=fork()) {/*handle error*/}
if(!PID2) _exit(code_for_child2());
/*continue the parent's work*/
推荐阅读
- visual-studio-code - 调试时如何在“变量列表”中搜索道具/变量?
- nginx - 自定义 Nginx 反向代理后面的 Meteor 乘客独立
- laravel - Laravel 每天从数据透视表中得到锻炼
- typescript - 使用字符串文字作为计算属性名称的模板参数
- python - 如何修补从另一个模块导入的函数
- android - 将flutter模块添加到android项目时无法触发onActivityResult
- c# - C# BigInteger 按位异或返回额外的数字
- javascript - 更改上下文后使用新数据渲染页面
- php - 未定义的变量,而我定义它
- php - 将库中的变量加载到控制器文件中?