简体   繁体   English

如何将变量从子进程fork()传递到其父进程fork()

[英]How to pass a variable from a child process fork() to his parent process fork()

The following code outputs a series of processes, exactly what it does is: 以下代码输出一系列过程,它的确切作用是:

                 _PARENT_
               /          \
              /            \
        child_2             child_3
       /       \            /      \
      /         \          /        \
     /           \        /          \
g_child_4    g_child_5  g_child_6    g_child_7

This is the output: 这是输出:

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).

My question is, how can I get the grandchild_4 and 5 pass to child_2 their position values and child_2 sum it and pas it to parent? 我的问题是,如何获得grandchild_4和5传递给child_2的位置值,然后child_2将其求和并将其传递给父级? And same thing with grandchilds_6 and 7 passing their position values to child_3 and sum it to pass it to parent? 同样,grandchilds_6和7将其位置值传递给child_3并将其求和以将其传递给父项吗?

All I'm trying to get is to be able to print the sum of the position values of all grandchilds so at the output I can have: 我要做的就是能够打印所有孙子孙的位置值的总和,因此在输出中我可以得到:

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.

Note: no pipes, FIFOs or maps can be used. 注意:不能使用管道,FIFO或映射。
This is my code: 这是我的代码:

#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);    
}

The general term for what you're looking for is interprocess communication . 您要查找的通用术语是进程间通信 There are many ways to pull this off: shared memory, pipes, FIFOs, and more. 有很多方法可以实现这一点:共享内存,管道,FIFO等。

For your purposes, I might recommend creating a simple array in shared memory (see the man page for shmget ). 为了您的目的,我建议您在共享内存中创建一个简单的数组(请参见手册页中的shmget )。 Each process can fill in a specific position in the array with its position, and then you can use a POSIX semaphore (see sem_wait and sem_post ) to signal the parent process that the position has been filled in. The parent process can then access the array and see what position its child process occupies. 每个进程都可以使用其位置填充数组中的特定位置,然后可以使用POSIX信号量(请参见sem_waitsem_post )向父进程发出已填充该位置的信号。然后,父进程可以访问数组。并查看其子进程所处的位置。

If the sums involved are all guaranteed to be tiny, as in your example, then the children can return them via their exit codes, which you can obtain via the status value filled in by wait() when you pass it a non- NULL pointer (use the WEXITSTATUS() macro to obtain the exit code from the status). 如果保证所涉及的总和很小(如您的示例中所示),则子代可以通过其退出代码将它们返回,当您向其传递非NULL指针时,可以通过wait()填充的状态值来获得这些退出代码。 (使用WEXITSTATUS()宏从状态获取退出代码)。 This works only if you can be confident that none of the sums will exceed 127. 仅当您可以确定总和不超过127时,此方法才有效。

In the general case, you would probably establish a pipe for each child process by which it could write its result for the parent to read. 在一般情况下,您可能会为每个子进程建立一个管道,通过该管道可以将其结果写入父进程以供读取。 You could also set up shared memory by which each child could communicate its result, but this is trickier to set up and use properly, and it obviates the sub-process tree structure that you've gone to such trouble to create. 您还可以设置共享内存,每个孩子都可以通过该共享内存传达其结果,但是要正确设置和使用它比较棘手,并且可以避免创建麻烦的子流程树结构。

You need to use a semaphore, or some sort of shared memory. 您需要使用信号量或某种共享内存。 You have a block of shared memory, using a lock so only one process may access it at a time 您有一块共享内存,使用了一个锁,因此一次只能有一个进程访问它

A decent reference to shared memory: http://www.cs.cf.ac.uk/Dave/C/node27.html 对共享内存的体面参考: http : //www.cs.cf.ac.uk/Dave/C/node27.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM