c-使用管道传递结构信息



我正在尝试使用管道在父进程和子进程之间传递结构信息,但无法捕捉到我的错误。如果你能给我指明解决问题的方法或提出建议,我将不胜感激。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
struct Student {
int ID;
char Name[10];
};

int main() {
int i;
struct Student student[5] = {0, ''};
char *Names[5] = {"David", "Roger", "Syd", "Richard", "Nick"};
pid_t pid = fork();
char *info[3];
int fd[2];
pipe(fd);
if (pid < 0) {
printf("Fork failed.");
exit(1);
}

else if (pid == 0) {// Child
close(fd[1]);
printf("Child Process: n");
for (i = 0; i < 5; ++i) {
student[i].ID = i + 1;
strcpy(student[i].Name, Names[i]);
}
write(fd[0], student[0].ID, sizeof(int));
for (i = 0; i < 5; ++i) {
printf("Student name is: %s, ID is: %dn", student[i].Name, student[i].ID);
}
printf("Child Process has been completed.n");

}
else {// Parent
wait(NULL);
close(fd[0]);

read(fd[1], student[0].ID, sizeof(student));
printf("nParent Process Printn");
for (i = 0; i < 5; ++i) {
printf("Student name is: %s, ID is: %dn", student[i].Name, student[i].ID);
}
}

return 0;
}

输出为:

子进程:
学生名称为:David,ID为:1
学习名称为:Roger,ID为2
课程名称为:Syd,ID为3
教学名称为:Richard,ID为4
学校名称为:Nick,ID为5
子进程已完成。

父进程打印
学生名称为:,ID为:0
学习名称为:、ID为:0
课程名称为:

我修复了以下问题:

  1. student的初始化错误。将范围缩小到子级和父级,并仅初始化这两个变量以关注手头的问题
  2. 客户端和服务器之间使用的交换管道
  3. 修正了发送每个学生id的写入(整数用作地址,学生数组不是索引(
  4. 固定读取每个学生id(整数用作地址,不在循环中读取(
  5. i的作用域缩减为循环变量
  6. 增强了发送和接收Name的功能
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
struct Student {
int ID;
char Name[10];
};
int main() {
int fd[2];
if(pipe(fd)) {
printf("pipe failedn");
return 1;
}
switch(fork()) {
case -1:
printf("Fork failed.");
return 1;
break;
case 0: {
close(fd[0]);
struct Student student[5] = {
{ 1, "David" },
{ 2, "Roger" },
{ 3, "Syd" },
{ 4, "Richard" },
{ 5, "Nick" },
};
printf("Child Process: n");
for (int i = 0; i < 5; i++) {
printf("Student name is: %s, ID is: %dn", student[i].Name, student[i].ID);
write(fd[1], &student[i].ID, sizeof(student[i].ID));
size_t len = strlen(student[i].Name);
write(fd[1], &len, sizeof(len));
write(fd[1], student[i].Name, len);
}
printf("Child Process has been completed.n");
break;
}
default: {
struct Student student[5] = { 0 };
wait(NULL);
close(fd[1]);
printf("nParent Process Printn");
for (int i = 0; i < 5; i++) {
read(fd[0], &student[i].ID, sizeof(student[i].ID));
size_t len;
read(fd[0], &len, sizeof(len));
read(fd[0], student[i].Name, len);
printf("Student name is: %s, ID is: %dn", student[i].Name, student[i].ID);
}
break;
}
}
return 0;
}

以及结果输出:

Child Process:
Student name is: David, ID is: 1
Student name is: Roger, ID is: 2
Student name is: Syd, ID is: 3
Student name is: Richard, ID is: 4
Student name is: Nick, ID is: 5
Child Process has been completed.
Parent Process Print
Student name is: David, ID is: 1
Student name is: Roger, ID is: 2
Student name is: Syd, ID is: 3
Student name is: Richard, ID is: 4
Student name is: Nick, ID is: 5

最新更新