我正在尝试 fork 一个子项并向其写入一个结构,但由于某种原因写入失败。这是我到目前为止所得到的:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
pid_t pid;
int pfd[2];
int rv;
if(pipe(pfd) == -1){
printf("Pipe failed\n");
}
struct t{
int count[26];
char array[4];
};
struct t st;
if((pid = fork()) < 0){
printf("Fork error\n");
}else if(pid == 0){
close(pfd[1]);
rv = read(pfd[0],st,sizeof(struct t));
printf("Read string: %d\n",rv);
}else{
int i = 0;
for(i = 0; i < 26; i++){
st.count[i] = i;
}
for(i = 0; i < 3; i++){
st.array[i] = 'A';
}
st.array[3] = '\0';
close(pfd[0]);
rv = write(pfd[1],st,sizeof(struct t));
printf("wrote: %d",rv);
close(pfd[1]);
}
}
这让我整夜都难受。我怀疑这与我没有完全理解结构体指针有关。我打印了 sizeof(struct t) ,它返回 108 个字节(如预期),我认为 st 是指向结构开头的指针,这意味着写入命令将从那里开始并写入前 108 个字节,但显然情况并非如此。我错过了什么?
最佳答案
尝试&st
。 st
是结构本身。 &
从中取出一个指针。
您可能需要启用(或注意)编译器警告。将 -Wall
或 -Wall -Wextra
添加到编译命令中。
您需要包含 read
函数的头文件。
#include <unistd.h>
现在您应该收到错误消息。
关于c - 通过管道失败将结构写入子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15984040/