C 写和读的错误是什么?
这是一个关于管道和进程的小C程序,父进程将创建两个子进程,第一个进程将读取链中的数字,第二个进程将读取字母。我从问单词开始,我没有添加保护这只是一个测试,假设大约20个字母,然后父亲进程将数字写在第一个管道中,字母写在第二个管道中,然后他将使用fork()创建一个孩子,如果他是孩子,他将读取第一个管道中的数字,如果他是父亲,然后,他将创建另一个孩子来阅读这些字母C 写和读的错误是什么?,c,fork,pipe,C,Fork,Pipe,这是一个关于管道和进程的小C程序,父进程将创建两个子进程,第一个进程将读取链中的数字,第二个进程将读取字母。我从问单词开始,我没有添加保护这只是一个测试,假设大约20个字母,然后父亲进程将数字写在第一个管道中,字母写在第二个管道中,然后他将使用fork()创建一个孩子,如果他是孩子,他将读取第一个管道中的数字,如果他是父亲,然后,他将创建另一个孩子来阅读这些字母 # include <stdio.h> # include <unistd.h> # include <
# 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);
}
}
write
和read
的原型是
ssize_t write(int fd, const void *buf, size_t count);
ssize_t read(int fd, void *buf, size_t count);
写入/读取
的参数2应该是指针。但是您发送的是一个字符(实际上是一个整数)word[i]
和numbers[i]
即使您的strlen也存在同样的问题
另外,将word
声明为数组,而不仅仅是指针。否则,您将写入指针指向的任意位置。或者,如果你想把它作为一个指针,就给它一些内存
在所有这些之后,只需将word
、numbers
而不是numbers[j]
或words[i]
传递给正在抱怨的函数即可
编辑:也是您最后的for
语句for(i=0;i而不是:
write(fd1[1],word[i],2);
这样做:
write(fd1[1],(void*)&word[i],2);
…也就是说,传递一个指向数据位置的指针,而不是数据本身的值。我使用read(fd2[0],&caracters[k],1);什么行号?它对应什么行?它需要一个固定的右括号。但在执行后,它要求输入单词,我键入它,然后显示两个printf(现在父亲将写入…)然后没有其他内容了……我使用了read(fd2[0],&caracters[k],1);已修复。但执行后,它要求输入单词,我键入它,然后它显示2个printfs(现在父亲将写入……)那么就没有别的了……@AliBassam你做了我建议的所有其他更改了吗?为什么要尝试在循环中按字符写入字符呢?只需将其作为单个缓冲区写入即可
write(fd1[1],(void*)&word[i],2);