- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
下面的代码输出了一系列的过程,它到底做了什么:
_PARENT_
/ \
/ \
child_2 child_3
/ \ / \
/ \ / \
/ \ / \
g_child_4 g_child_5 g_child_6 g_child_7
这是输出:
Process Pid: 929 PPid: 928 (position: 2).
Process Pid: 930 PPid: 928 (position: 3).
Process Pid: 931 PPid: 929 (position: 4).
Process Pid: 932 PPid: 929 (position: 5).
Process Pid: 934 PPid: 930 (position: 7).
Process Pid: 933 PPid: 930 (position: 6).
我的问题是,如何让 grandchild_4 和 5 将它们的位置值传递给 child_2,然后 child_2 将其求和并传递给父级? grandchilds_6 和 grandchilds_6 和 7 将它们的位置值传递给 child_3 并将其求和以传递给父级也是一样的吗?
我想要得到的只是能够打印所有孙子的位置值的总和,所以在输出中我可以拥有:
Process Pid: 929 PPid: 928 (position: 2).
Process Pid: 930 PPid: 928 (position: 3).
Process Pid: 931 PPid: 929 (position: 4).
Process Pid: 932 PPid: 929 (position: 5).
Process Pid: 934 PPid: 930 (position: 7).
Process Pid: 933 PPid: 930 (position: 6).
Result 22.
注意:不能使用管道、FIFO 或映射。
这是我的代码:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <math.h>
/*
* NUMBER OF LEVELS TO BE CREATED
*/
#define NUM_LEVEL 2
/*
* Child launcher
*/
int launchChild(int nivel,int n){
//sleep(1);
if(nivel>0) printf("Process Pid: %d PPid: %d (position: %d).\n",getpid(),getppid(), n+1);
if(nivel<NUM_LEVEL){
pid_t process = fork();//Child or parent?
if(process!=0){// Parent
process=fork();//Child or parent?
if(process==0){//Child
launchChild(nivel+1,2*n+2);
wait(NULL);
}
}
else{//Child
launchChild(nivel+1,2*n+1);
}
wait(NULL);
}
}
/*
* Main function
*/
int main(void){
launchChild(0,0);
}
最佳答案
您正在寻找的一般术语是进程间通信。有很多方法可以做到这一点:共享内存、管道、FIFO 等等。
出于您的目的,我可能建议在共享内存中创建一个简单的数组(参见 shmget
的手册页)。每个进程都可以用它的位置填充数组中的特定位置,然后您可以使用 POSIX 信号量(参见 sem_wait
和 sem_post
)向父进程发出信号位置已经填满,父进程就可以访问这个数组,看看它的子进程占据了什么位置。
关于c - 如何将变量从子进程 fork() 传递到他的父进程 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878650/
需要帮助将这些给定的数字打印成星号,但我是编程新手;我该怎么做? #include int main(void) { int a[5]={20,1,5,15,12}; int i=0
使用 Delphi XE 2 我试图确定缩放方向以将缩放效果应用于图像(TImage),但没有找到执行此操作的函数,并且图像的 OnGesture 事件中的 EventInfo 属性没有此信息. 我见
我不知道制服在内存中是如何表示的。 制服似乎会占用宝贵的寄存器空间,但它们最终会传入/通过/传出到全局内存中,对吗? 制服不用时情况会发生变化吗?编译器可以将它们优化掉吗?--在这种情况下,我已经将无
我正在尝试在名为“timeclock”的模型上记录“time_in”和“time_out”记录。这是我想做但无法开始工作的事情! 检查最后一个时钟条目,看看它是否同时填充了“time_in”和“tim
我想听听您如何解决这种编程任务!?每种类型(OPER = 1 类型)对应一种特定的信息。 这只是大约 10 个具有相同结构的规范之一。首选创建这些“转换器”(协议(protocol))的通用方法。 最
我正在使用 Rest API(NodeJS、Express)和 PostgreSQL 制作 React-Native 应用。 在我的本地机器上托管时一切正常。当 API 托管在我的机器上并且 Post
我是一名优秀的程序员,十分优秀!