如何在管道之间传递值

时间:2015-10-04 18:50:03

标签: c

所以我创建了10个进程,并在每个进程中添加了一堆随机数,以便每个进程都包含一个部分和。如何将部分金额传递回父流程?我有一点困难,任何帮助将不胜感激。感谢您

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <sys/wait.h>

int MAX_PROC = 10;
pid_t pids[10];

void childProcess(void);
void parentProcess(void);
int startChildren(void);

main() {
    srand(time(NULL));
    clock_t begin,end;
    double timeSpent;
    begin = clock();

    startChildren();

    end = clock();
    timeSpent = (double)(end-begin);
    //printf("\n Time taken: %f \n", timeSpent);
    return 0;
}

int startChildren(void) {
    int i = 0;
    for (i = 0; i < MAX_PROC; ++i) {
        pids[i] = fork();
        if (pids[i] == 0) {
            childProcess();
            return(0);
        }
    }

    int status;
    pid_t pid;
    while (MAX_PROC > 0) {
        pid = wait(&status);
        MAX_PROC--;
    }
    parentProcess();
    return(0);
}

void  childProcess(void)
{
    int i = 0;
    int partial = 0;

    for(i=0; i<10000; i++) {
        int r = rand() % 101;
        partial += r;
    }   
}

void  parentProcess(void)
{
    printf("*** Parent is done ***\n");
}

1 个答案:

答案 0 :(得分:0)

以下是如何使用socketpair()在父/子进程之间传递数据的示例(在类UNIX操作系统中):

#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>

#define DATA1 "In Xanadu, did Kublai Khan . . ."
#define DATA2 "A stately pleasure dome decree . . ."


/*
 * This program creates a pair of connected sockets, then forks and
 * communicates over them.  This is very similar to communication with pipes;
 * however, socketpairs are two-way communications objects. Therefore,
 * this program can send messages in both directions.
 */


main()
{
    int sockets[2], child;
    char buf[1024];


    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) {
        perror("opening stream socket pair");
        exit(1);
    }


    if ((child = fork()) == -1)
        perror("fork");
    else if (child) {   /* This is the parent. */
        close(sockets[0]);
        if (read(sockets[1], buf, 1024, 0) < 0)
            perror("reading stream message");
        printf("-->%s\n", buf);
        if (write(sockets[1], DATA2, sizeof(DATA2)) < 0)
            perror("writing stream message");
        close(sockets[1]);
    } else {        /* This is the child. */
        close(sockets[1]);
        if (write(sockets[0], DATA1, sizeof(DATA1)) < 0)
            perror("writing stream message");
        if (read(sockets[0], buf, 1024, 0) < 0)
            perror("reading stream message");
        printf("-->%s\n", buf);
        close(sockets[0]);
    }
}