c - 分叉进程与套接字通信

时间:2014-07-08 03:25:39

标签: c sockets process fork

我正在尝试创建一个套接字,该套接字与已分叉的两个子进程a和b进行通信。我需要它通过socket sc进行通信。作为一个起点,我试图让Process a通过sc套接字向Process b写一条消息,但到目前为止我尝试的所有内容都会导致打印错误消息。

以下是我的代码。关于如何最终使其发挥作用的任何想法? (我的最终目标是阅读和撰写不止一条信息,因此任何建议都是明确的奖励。)提前感谢您提供的任何帮助。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>

int main() {
    pid_t a, b;
    int sc;
    struct sockaddr server = {AF_UNIX, "server"};
    sc = socket(AF_UNIX, SOCK_STREAM, 0);
    bind(sc, &server, sizeof(server));
    listen(sc, 1);

    if ((a = fork()) == 0) {
        struct sockaddr me = {AF_UNIX, "ProcessA"};
        struct sockaddr there = server;
        int s = socket(AF_UNIX, SOCK_STREAM, 0);
        char buffer[256];
        sprintf(buffer, "test");
        if (bind(s, &me, sizeof(me)) < 0) {printf("Error binding\n"); exit(1);}
        if (connect(s, &there, sizeof(there)) < 0) printf("Error connecting\n");
        write(s, buffer, strlen(buffer) + 1);
        printf("Process A\n");
        exit(0);
    }
    else if ((b = fork()) == 0) {
        struct sockaddr address;
        int length;
        length = sizeof(address);
        int c, n;
        char buffer[256];
        if ((c = accept(sc, &address, &length)) < 0) {printf("Error accepting\n"); exit(1);}
        if ((n = read(c, buffer, 255)) < 0) {printf("Error reading\n"); exit(1);}
        printf("Log Process\n");
        printf("%s\n", buffer);
        exit(0);
    }
    return 0;
}

我不断收到消息“错误绑定”和“错误接受” - 再一次,谢谢。

1 个答案:

答案 0 :(得分:5)

来自Beej's Guide

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>

int main(void)
{
    int sv[2]; /* the pair of socket descriptors */
    char buf; /* for data exchange between processes */

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

    if (!fork()) {  /* child */
        read(sv[1], &buf, 1);
        printf("child: read '%c'\n", buf);
        buf = toupper(buf);  /* make it uppercase */
        write(sv[1], &buf, 1);
        printf("child: sent '%c'\n", buf);

    } else { /* parent */
        write(sv[0], "b", 1);
        printf("parent: sent 'b'\n");
        read(sv[0], &buf, 1);
        printf("parent: read '%c'\n", buf);
        wait(NULL); /* wait for child to die */
    }

    return 0;
}

注意:考虑在子案例中关闭您未使用的套接字:close(sv[0]);;在父案件中close(sv[1]);