【问题标题】:Creating a tree using fork() with a number of children differs in value and changes each time使用具有多个子项的 fork() 创建树的值不同,并且每次都会更改
【发布时间】: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=&current_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

【问题讨论】:

  • 正确的术语是“孩子”和“父母”。
  • 子进程中的变量更改不会反映在父进程中,反之亦然。您不能使用普通内存中的变量在进程之间进行通信。

标签: c linux fork


【解决方案1】:

您的代码中没有任何地方使用任何类型的进程间通信机制。如果一个进程修改变量在另一个进程中更改其值,则会出现混乱。没有代码可以工作——即使i = i + 1 被两个进程同时执行也会失败。

通过标识符直接访问变量和通过指针间接访问变量之间没有语义上的区别。仅仅使用指针并不会突然调用某种神奇的同步形式,以确保在一个进程中修改变量而另一个进程可能正在访问它。

如果你想在进程之间共享信息,你必须使用一些提供同步和安全的机制。您可以使用文件、套接字、管道、共享内存(通过某种锁定或排他性机制来避免数据争用)或任何其他可用的东西。

但您必须准确指定哪些内容将共享,哪些内容不共享。

(从技术上讲,您确实使用wait,这是一种进程间通信和同步的形式。)

【讨论】:

  • 我明白.. 谢谢!我会尝试处理文件
猜你喜欢
  • 2017-12-15
  • 1970-01-01
  • 2020-06-12
  • 2013-07-08
  • 2015-04-15
  • 1970-01-01
  • 1970-01-01
  • 2018-02-19
  • 1970-01-01
相关资源
最近更新 更多