【发布时间】:2021-07-08 22:14:25
【问题描述】:
我尝试根据数组中的值创建一个进程树。 因此,对于每个进程,其子进程的数量将是在数组中此单元格中找到的数量。 所以我保留了一个数字,用来记录我目前有有多少孩子以及现在正在运行的进程。
问题是,为了让进程相互通信,我将这些值保存在内存中的地址(指针)中,但那里的东西仍然没有同步。
我附上一张数组 {2,3,1,0,0,0} 的图片:
这是我的代码:
#include <stdio.h>
#include <unistd.h>
#include <wait.h>
int main(int argc, char* argv){
int current_id=0;// id of the process running now
int son_counter=0; // id for son
int * p_current_id=¤t_id;
int * p_son_counter=&son_counter;
int my_num=0;//process num
int arr[6]={2,1,2,1,0,0};
for(int i=0;i<arr[*p_current_id];i++)
{
pid_t iam=fork();
if(iam==0)//son
{
++(*p_son_counter);
printf("p_son_counter: %d\n", *p_son_counter);
my_num=(*p_son_counter);//++ for the num of son
//printf("p_son_counter: %d\n", *p_son_counter);
while(*p_current_id<my_num)
{
sleep(1);
}
printf("Im process %d - %d and ready to start!\n", my_num, getpid());
i=0;
}
else if(iam!=0)//father
{
printf("im the father %d - %d & i created process %d\n", my_num, getpid(), iam);
}
}
printf("p_current_id: %d\n", *p_current_id);
(*p_current_id)++;
printf("p_current_id: %d\n", *p_current_id);
printf("process %d - %d finished his job!",my_num, getpid());
while(wait(NULL)>0);
//printf("Process id %d, parent process id %d, my num : %d \n", getpid(), getppid(), my_id);
return 0;
}
出于某种原因,这是我的输出...
im the father 0 - 8186 & i created process 8187
im the father 0 - 8186 & i created process 8188
p_current_id:0
p_current_id:1
p_son_counter:1
p_son_counter:1
【问题讨论】:
-
正确的术语是“孩子”和“父母”。
-
子进程中的变量更改不会反映在父进程中,反之亦然。您不能使用普通内存中的变量在进程之间进行通信。