fork+pipe,多个子进程写数据,父进程读数据

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

static void showReturnStatus(pid_t childpid, int status)
{
    if (WIFEXITED(status) && !WEXITSTATUS(status))
        printf("-----------------------------------------------------------Child %ld terminated normally\n", (long)childpid);
    else if (WIFEXITED(status))
        printf("-------------Child %ld terminated with return status %d\n", (long)childpid, WEXITSTATUS(status));
    else if (WIFSIGNALED(status))
        printf("---------------Child %ld terminated due to uncaught signal %d\n", (long)childpid, WTERMSIG(status));
    else if (WIFSTOPPED(status))
        printf("-----------------Child %ld stopped due to signal %d\n", (long)childpid, WSTOPSIG(status));
}

int main(int argc, char *argv[])
{
    srand(time(0));
    int arraySize = 72;
    int numProcess = 6;
    int array[arraySize];
    int fd[2];
    const char *arg0 = (argc == 0) ? "pipe79" : argv[0];    /* Use argc */

    assert(arraySize % numProcess == 0);
    int numPerProcess = arraySize / numProcess;

    if (pipe(fd) == -1)
    {
        fprintf(stderr, "%s: failed to create a pipe\n", arg0);
        exit(EXIT_FAILURE);
    }

  

  int sum = 0;
    for (int i = 0; i < arraySize; i++)
    {
        array[i] = (rand() % 99) + 1;
        sum += array[i];
    }

    int width = 0;
    const char *pad = "";
    for (int i = 0; i < arraySize; i++)
    {
        width += printf("%s%2d: %2d", pad, i, array[i]);
        pad = ", ";
        if (width > 72)
        {
            putchar('\n');
            width = 0;
            pad = "";
        }
    }
    if (width > 0)
        putchar('\n');
    printf("Sum calculated by parent: %d\n", sum);
    printf("Parent PID[%d]\n", getpid());

    for (int childP = 0; childP < numProcess; childP++)
    {
        int child = fork();
        if (child < 0)
        {
            fprintf(stderr, "%s: failed to fork child %d\n", arg0, childP + 1);
            exit(EXIT_FAILURE);
        }
        if (child == 0)
        {
            close(fd[0]);
            int childSum = 0;

            int byte_to_write = 0;
            int start = childP * numPerProcess;
            int stop = start + numPerProcess;

          //printf("Child PID %d: processing rows %d..%d\n", getpid(), start, stop - 1);
            for (int i = start; i < stop; i++)
                childSum += array[i];
            //printf("Child Process No [%d] PID [%d] Return Sum : %d\n", childP, getpid(), childSum);

             char sztemp[1024] = {0};
             sprintf(sztemp,"%s%d","hello",childP); 
            byte_to_write = strlen(sztemp) + 1;

            //if (write(fd[1], &childSum, sizeof(childSum)) != sizeof(childSum))
            if (write(fd[1], sztemp,byte_to_write) != byte_to_write)
            {
                fprintf(stderr, "Child Process No [%d] PID [%d] failed to write to the pipe\n",
                        childP, getpid());
                exit(EXIT_FAILURE);
            }
            close(fd[1]);
            exit(0);
        }
    }

    close(fd[1]);

    sum = 0;
    pid_t pid;
    int status = 0;
    int count = 0;
    while ((pid = wait(&status)) != -1)
    {
        int number;
        char info[1024] = {0};
        showReturnStatus(pid, status);
         //注意read每次读取的字节大小,可能一次性读取更多,导致下次输出没有内容
        if(read(fd[0], info, 7) != 13) //读取内容"hellox"
        {
            fprintf(stderr, "%s: parent process got a short read on the pipe\n", arg0);
            exit(EXIT_FAILURE);

}
        /*
         if (read(fd[0], &number, sizeof(number)) != sizeof(number))
        {
            fprintf(stderr, "%s: parent process got a short read on the pipe\n", arg0);
            exit(EXIT_FAILURE);
        }*/
        //printf("count= %d,sum from pipe: %d\n",count++, number);
        printf("count= %d,info: %s\n",count++, info);
        sum += number;
    }

    printf("Parent Process with PID [%d] accumulated sum : %d\n", getpid(), sum);
    return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值