#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
#define SIZE 50
struct record {
int freq;
char word[SIZE];
};
int main(){
int number_process = 3;
int pipes[number_process][2];
struct record r1;
r1.freq = 10;
strcpy(r1.word, "Cat");
struct record r2;
r2.freq = 20;
strcpy(r2.word, "Elephant");
struct record r3;
r3.freq = 30;
strcpy(r3.word, "Dragon");
struct record records_array[3] = {r1, r2, r3};
for (int i = 0; i < number_process; i++){
if (pipe(pipes[i]) == -1){
perror("pipe");
exit(1);
}
// Create children.
pid_t fork_result = fork();
if (fork_result == -1){
perror("Parent fork");
exit(1);
} else if (fork_result == 0){
if (close(pipes[i][0]) == -1){
perror("Child closes reading port");
exit(1);
}
// Later children is going to close all reading port from pipe that parent creates.
for (int child_no = 0; child_no < i; child_no++) {
if (close(pipes[child_no][0]) == -1) {
perror("close reading ends of previously forked children");
exit(1);
}
}
// Now, I am trying to write each strct record member from the above array into the pipe
// when I run the program, it won't allow me to do so because of bad file descriptor exception.
for (int j = 0; j < number_process; i++){
if (write(pipes[i][1], &(records_array[j]), sizeof(struct record)) == -1){
perror("write from child to pipe");
exit(1);
}
}
// Finishing writing, close the writing end in pipe.
if (close(pipes[i][1]) == -1){
perror("Child closes writing port");
exit(1);
}
// Terminate the process.
exit(0);
} else {
// Parent is closing all the writing ends in pipe.
if (close(pipes[i][1]) == -1){
perror("Parent close writing");
exit(1);
}
}
}
struct record buffer;
for (int i = 0; i < number_process; i++){
// Parent reads from the pipe.
if (read(pipes[i][0], &buffer, sizeof(struct record)) == -1){
perror("parent read");
exit(1);
}
printf("buffer.freq = %d\n", buffer.freq);
printf("buffer.word = %s\n", buffer.word);
}
return 0;
}
我是系统编程的新手,以下代码是我为了解管道功能而实施的一些实践。我对代码有一些疑问:
1)是否有任何系统调用或库调用可以帮助我确保要写入管道的内容实际上已成功写入管道?换句话说,我有什么方法可以检查我写入管道的内容/数据吗?
2)我觉得我的父母阅读部分实现不正确,当我运行此代码时,我的父母阅读部分连续读取了3项相同的内容,尽管每次阅读都应该是不同的内容。
3)当我尝试从父进程的管道中读取内容时,我遇到了地址错误的问题,发生此错误的原因是什么?
有人可以帮助我了解这些内容吗?非常感谢。
答案 0 :(得分:2)
您有一个简单的剪切粘贴错误。 for (int j = 0; j < number_process; i++){
您需要递增j
。