c - 通过管道失败将结构写入子级

标签 c struct ipc pipe

我正在尝试 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 个字节,但显然情况并非如此。我错过了什么?

最佳答案

尝试&stst 是结构本身。 & 从中取出一个指针。

您可能需要启用(或注意)编译器警告。将 -Wall-Wall -Wextra 添加到编译命令中。

<小时/>

您需要包含 read 函数的头文件。

#include <unistd.h>

现在您应该收到错误消息。

关于c - 通过管道失败将结构写入子级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15984040/

相关文章:

c++ - 服务和用户模式进程之间的共享全局事件不起作用

c# - 限制 NamedPipeServerStream 的范围

c - 将变量的值传递给 C 中的宏

在函数返回之间进行选择

c# - 在范围末尾执行清理的结构是一个好的 C# 模式吗?

c - 我需要在 Swift 中 memset 一个 C 结构吗?

c - 声明临时结构作为参数传递——结构被重写。如何在新的内存位置声明该结构?

c - 结构指针数组段错误

c - 如何从c中的日期时间字符串中删除空格

c++ - Unix 用户空间中的实时 IPC