0

这是一个关于管道和进程的小 C 程序,父进程将创建 2 个子进程,第一个将从链中读取数字,第二个将读取字母。我一开始是要求 WORD,我没有加保护,这只是一个测试,所以假设大约 20 个字母,然后父进程将在第一个管道中写入数字,在第二个管道中写入字母,然后他将创建使用 fork() 的孩子,如果他是孩子,他将从第一个管道中读取数字,如果他是父亲,那么他将创建另一个孩子来阅读字母。

# include <stdio.h>
# include <unistd.h>
# include <string.h>
# include <fcntl.h>

main()
{
    printf("I am the father, I will create 2 sons, the first will read the numbers , the second will read the letters\n");
    char * word;
    printf("please type the word: \n");
    scanf("%s",word);
    printf("Now 2 pipes will be created\n");
    int fd1[2];
    int fd2[2];
    pipe(fd1); pipe(fd2);
    printf("Now the father will write numbers in the first pipe, and letters in the second\n");
    int i;
    char numbers[20]; int j=0;
    char caracters[20]; int k=0;
    for (i=0;i<20;i++)
    {
        if(word[i]>='0' && word[i]<='9') //if number
        {
            close(fd1[0]); //closing reading
            write(fd1[1],word[i],2);

        }
        else
        {
            close(fd2[0]);  
            write(fd2[1],word[i],2);
        }

    }
    printf("The father has wrote in the 2 pipes, now its time for the sons\n");
    int f=fork();
    if(f==0) //first son
    {
        for(i=0;i<20;i++) {         
            close(fd1[1]); //closing writing
            read(fd1[0],numbers[j],strlen(numbers[j])+1);
            j++;

        }
        printf("first son read everything, he got %d Numbers\n", j);
    }
    else
    {
        f=fork();
        if(f==0)
        {
            for(i=0;i<20;i++) {         
            close(fd2[1]); //closing writing
            read(fd2[0],caracters[k],strlen(caracters[k])+1);
            k++;

        }   
        printf("second son read everything, he got %d caracters\n", j);
    }
}

编译后:

In function 'main':
Line 25: warning: passing argument 2 of 'write' makes pointer from integer without a cast
Line 31: warning: passing argument 2 of 'write' makes pointer from integer without a cast
Line 41: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast
Line 41: warning: passing argument 2 of 'read' makes pointer from integer without a cast
Line 54: warning: passing argument 1 of 'strlen' makes pointer from integer without a cast
Line 54: warning: passing argument 2 of 'read' makes pointer from integer without a cast
Line 60: error: expected declaration or statement at end of input
4

2 回答 2

3

write和的原型read

ssize_t write(int fd, const void *buf, size_t count);

ssize_t read(int fd, void *buf, size_t count);

write/的参数 2read应该是一个指针。但是您发送的是一个字符(实际上是一个整数)word[i]并且numbers[i]

即使你的也有同样的问题strlen

此外,声明word为一个数组,而不仅仅是一个指针。否则,您将写入指针指向的任何随机位置。或者,如果您想将其保留为指针,请为其保留malloc一些内存。

毕竟,只需将word,numbers而不是numbers[j]或传递words[i]给您抱怨的函数

编辑:您的最后一条for语句也for(i=0;i<20;i++)缺少右括号,因此出现Line 60: error: expected declaration or statement at end of input错误

于 2012-04-22T19:02:26.347 回答
0

代替:

write(fd1[1],word[i],2);

做这个:

write(fd1[1],(void*)&word[i],2);

...即,将指针传递给数据的位置,而不是数据本身的值。

于 2012-04-22T19:04:22.693 回答