子进程没有从管道中读取正确的值

时间:2017-12-27 17:00:36

标签: c arrays pipe fork

我有两个过程:

Master.c

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

void error(char *m)
{
    write(2, m, strlen(m));
    write(2, "\n", 1);
    write(2, strerror(errno), strlen(strerror(errno))); exit(1);

}

int main(int argc, char *argv[])
{
   int fd1[2],fd2[0];
int numeros[1000];
int val;
int wpid;
int status = 0;

signal(SIGINT, sigint_handler);

if (pipe(fd1) < 0) error("Pipe creation");

pid1 = fork();

switch (pid1) {
        case -1: error("Fork 1");
        case 0: /* Procés fill */
              close(0);
              dup(fd1[0]);
              close(fd1[1]);
              execv("./Second",NULL);

        default: /* Procés pare */
            break;
}

close(1);
dup(fd1[1]);
close(fd1[0]);

for( val = 0; val <= 1000; val++)
     numeros[val]=val;


write(1, numeros, sizeof(numeros)+1);

while ((wpid = wait(&status)) > 0);

exit(EXIT_SUCCESS);

return 0;
}

第二

int main(int argc, char *argv[])
{
    int i,k = 0;
    int num_rev[1000];
    int num_pair[1000];

    read(0, num_rev, sizeof(num_rev));

    for( i = 1; i <= 1000; i++){
        int temp = num_rev[i];
        printf("Child(%d) received value: %d\n", getpid(), temp);
        int m = temp % 2;
        if (m != 0){
            num_pair[k]=temp;
            printf("Second filtered value: %d\n", temp);
            k++;
        }
    }

    exit(EXIT_SUCCESS);

    return 0;
}

首先作为父级,创建Second作为子级,并使用管道,重定向stdout和stdin,在数组中发送1到1000之间的整数值。我跟着这篇文章作为例子:

Using a Pipe to Write and Read Array of Int

但是第二个进程正在接收意外值:

Child(2370) received value: 32766
Child(2370) received value: 6
Child(2370) received value: 0
Child(2370) received value: 14
Child(2370) received value: 0
Child(2370) received value: 354020744
Child(2370) received value: 1

感谢。

0 个答案:

没有答案