c - 将值从子进程传递到父进程

标签 c linux fork parent-child

我有这段代码应该创建三个子进程,每个子进程将执行一个小的数学运算。然后, parent 应该使用所有子进程的结果并得到最终答案,但我找不到一种方法来实际读取 parent 的 child 的结果。有办法做到这一点吗?

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main(void)
{
   int pid1, pid2, pid3, status;
   int a=1, b=2, c=5, d=4, e=6, f=3, g;
   int t1, t2, t3;

   printf("Hello World!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n");
   printf("Here I am  before use of forking\n");
   printf("I am the PARENT process and pid is : %d\n",getpid());

   pid1 = fork( );
   if (pid1 == 0)
   {      
    printf("\n\nHere I am just after child forking1\n");
    printf("I am the Child process and pid1 is :%d\n",getpid());      
    printf("My parent's pid is :%d\n",getppid());   
    t1 = a+b;
    printf("The answer for t1 is: %d\n", t1);       
    exit(0);
   }
   else
   {
    wait(&status);
        printf("\nHere I am just after parent forking1\n");
        printf("I am the Parent process and pid is: %d\n",getpid());
   }

   pid2 = fork( );
   if (pid2 == 0)
   {      
    printf("\n\nHere I am just after child forking2\n");
    printf("I am the Child process and pid2 is :%d\n",getpid());      
    printf("My parent's pid is :%d\n",getppid());   
    t2 = c+d;
    printf("The answer for t2 is: %d\n", t2);   
    exit(0);    
   }
   else
   {
    wait(&status);
        printf("\nHere I am just after parent forking2\n");
        printf("I am the Parent process and pid is: %d\n",getpid());
   }

   pid3 = fork( );
   if (pid3 == 0)
   {      
    printf("\n\nHere I am just after child forking3\n");
    printf("I am the Child process and pid3 is :%d\n",getpid());      
    printf("My parent's pid is :%d\n",getppid());   
    t3 = e/f;   
    printf("The answer for t3 is: %d\n", t3);   
    exit(0);
   }
   else
   {
    wait(&status);
        printf("\nHere I am just after parent forkingALL\n");
        printf("I am the Parent process and pid is: %d\n",getpid());
   }


   printf("\n\nThe final answer for t1 is: %d\n", t1);
   printf("The final answer for t2 is: %d\n", t2);
   printf("The final answer for t3 is: %d\n", t3);


   g = t1*t2-t3;
   printf("The final answer for g is: %d\n", g);
}

最佳答案

您可以使用一种非常简单的技术来做到这一点,即共享内存。我将给出一个完整的例子来说明它是如何工作的。

首先,假设我想编写一个程序打印斐波那契数列中的前n(我知道这样做不合逻辑,但是这是一个简单的例子,所以每个人都可以理解)。

  1. 我有一个父级读取代表前 n 个项的整数值
  2. 然后父进程将创建一个子进程并将n传递给它
  3. 然后 child 应该计算前 n 项并将它们返回给 parent 。

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>

void printFibo(int n, int *fibo)
{
    int i;
    for(i=0; i<=n; i++)
        printf("%d -> %d\n" ,i, fibo[i]);
}

void computeFibo(int n, int *fibo) 
{
    int i;
    fibo[0] = 0;
    fibo[1] = 1;

    for (i=2; i<=n; i++) 
        fibo[i] = fibo[i-1] + fibo[i-2];
}

int main(int argc, char *argv[])
{
    pid_t childPID;
    int status;
    int shm_fd;
    int* shared_memory;
    int msize; // the size (in bytes) of the shared memory segment 
    const char *name = "FIBONACCI_SERIES";
    int n;

    if (argc!=2) 
    {
        fprintf(stderr, "usage: %s <Fibonacci number to be generated>\n", argv[0]);
        return -1;
    }

    n = atoi(argv[1]);
    if (n < 0) 
    {
        fprintf(stderr, "Illegal fibonacci number: %s\n", argv[1]);
        return -2;
    }

    // calculating the array size based on the number of terms being passed from child to parent
    msize = (n+2)*sizeof(int); 

    // open the memory
    shm_fd = shm_open (name, O_CREAT | O_EXCL | O_RDWR, S_IRWXU | S_IRWXG);
    if (shm_fd < 0) 
    {
        fprintf(stderr,"Error in shm_open()");
        return -3;
    }

    printf("Created shared memory object %s\n", name);

    // attach the shared memory segment
    ftruncate(shm_fd, msize);
    printf("shmat returned\n");

    // allocating the shared memory
    shared_memory = (int *) mmap(NULL, msize, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (shared_memory == NULL) 
    {
        fprintf(stderr,"Error in mmap()");
        return -3;
    }

    printf("Shared memory segment allocated correctly (%d bytes).\n", msize);

    shared_memory[0] = n;

    childPID=fork();
    if ( childPID == -1 ) 
    {
        fprintf(stderr, "Cannot proceed. fork() error");
        return -4;
    }
    if (childPID  == 0) 
    {
        // then we're the child process
        computeFibo(shared_memory[0],shared_memory+1);
        exit(0);
    }
    else
    {
        // parent will wait until the child finished
        wait(&status);

        // print the final results in the 
        printFibo(shared_memory[0], shared_memory+1);

        // now detach the shared memory segment
        shm_unlink(name);
    }
    return 0;
}

关于c - 将值从子进程传递到父进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499745/

相关文章:

c - printf 的包装器

linux - wget - "No route to host"运行armbian 的设备和android 热点之间的连接

linux - 如何使用 shell 比较两个文件中的列值?

c - 如何在启动可执行文件时隐藏密码

c - 如何阻止 execve 退出原始程序

c - 填充字符串留在 C 中的麻烦

将 FreeType 轴承转换为原点坐标

c - 如何 fork 并创建执行相同任务的特定数量的 child ?

c - C 中返回字符串的函数。为什么返回 null?

c++ over linux gcc 继承