c - 如何将变量从子进程 fork() 传递到他的父进程 fork()

标签 c linux

下面的代码输出了一系列的过程,它到底做了什么:

                 _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_waitsem_post)向父进程发出信号位置已经填满,父进程就可以访问这个数组,看看它的子进程占据了什么位置。

关于c - 如何将变量从子进程 fork() 传递到他的父进程 fork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33878650/

相关文章:

c - 了解实现低功耗蓝牙 CRC 的 C 代码

c - 如何获取telnet session 的远程端口号?

c - 段中的变量分配

linux - EXT4 是否已过时用于生产?

android - android 上的 docker(gnuroot debian)

php - 使用 PHP 更改符号链接(symbolic link)的目标

c - 具有扩展范围的浮点类型

c - 如何格式化用户输入的行?

java - 尽管流量低,但 Tomcat 上的平均负载异常高

linux - crontab - 没有任何反应