编辑代码

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <sys/wait.h>

#define BUFFER_SIZE 100

int main() {
    int sv[2];
    char buf[BUFFER_SIZE];
    char *parent_msg = "Hello from Parent";
    char *child_msg = "Hello from Child";

    if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
        perror("socketpair");
        exit(EXIT_FAILURE);
    }

    if (fork() == 0) {
        // 子进程
        close(sv[0]); // 关闭 sv[0]

        // 子进程向父进程发送数据
        write(sv[1], child_msg, strlen(child_msg) + 1);

        // 子进程从父进程读取数据
        read(sv[1], buf, sizeof(buf));
        printf("子进程收到的信息: %s\n", buf);

        close(sv[1]); // 关闭 sv[1]
        exit(EXIT_SUCCESS);
    } else {
        // 父进程
        close(sv[1]); // 关闭 sv[1]

        // 父进程向子进程发送数据
        write(sv[0], parent_msg, strlen(parent_msg) + 1);

        // 父进程从子进程读取数据
        read(sv[0], buf, sizeof(buf));
        printf("父进程收到的信息: %s\n", buf);

        close(sv[0]); // 关闭 sv[0]
        wait(NULL); // 等待子进程结束
    }

    return 0;
}