只有一个消息传递应用程序实例接收消息

时间:2011-12-04 04:26:02

标签: c linux sockets

在下面的代码中,我有3个函数(包括main)。 receive_loop函数轮询绑定到127.0.0.1的套接字,如果它收到任何消息,则打印它。 sender_loop使用scanf等待用户输入,当有输入时,它通过绑定到127.0.0.1的套接字发送它。 main在子级中分叉并运行sender_loop,在父级中运行receive_loop

现在,如果我编译代码并运行此可执行文件的两个实例,则无论哪个实例启动,都会先收到任一实例发送的消息。所以假设,instance1首先启动,然后instance1接收instance1 AND instance2发送的消息。我无法弄清楚为什么会发生这种情况,如果有人能解释一下(详情请见),我将不胜感激。感谢。

// INCLUDES NOT SHOWN

// recieve_loop
int receive_loop(int sock_fd, struct sockaddr *peer) {
    int isDataReady = 0;
    char buff[128]  = {0};
    struct pollfd poll_struct;

    poll_struct.fd     = sock_fd; 
    poll_struct.events = POLLIN;

    printf("reciever up\n");
    while (1) {
        while (1) {
            if (isDataReady > 0) break;
            isDataReady = poll(&poll_struct, 1, 500);
        }
        socklen_t sock_len = sizeof(struct sockaddr);
        recvfrom(sock_fd,
                buff,
                sizeof(buff),
                0,
                (struct sockaddr *)peer,
                &sock_len);

        printf("%s\n", buff);
    }

    return 0;
}


// sender_loop
int sender_loop(int sock_fd, struct sockaddr *peer) {
    char buff[32] = {0};

    printf("sender up\n");
    while (1) {
        scanf("%s", buff);

        int bytes_sent = sendto(sock_fd, buff, sizeof(buff), 0, (struct sockaddr *)peer, sizeof(struct sockaddr_in));

        if (bytes_sent <= 0)
            printf("sending message failed\n");

    }

    return 0;
}

int main(int argc, const char *argv[]) {
    // socket file descriptor to send data through
    int sock_fd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);

    // fill in the peer's address, loopback in this case
    struct sockaddr_in *peer = malloc(sizeof(struct sockaddr_in));
    peer->sin_family = AF_INET;
    peer->sin_port   = htons(11110);
    inet_pton(AF_INET, "127.0.0.1", &peer->sin_addr);

    bind(sock_fd, (struct sockaddr *)peer, sizeof(struct sockaddr_in)); 

    pid_t pid = fork();
    if (pid < 0) {
        printf("Couldn't fork, exiting");
        return 1;
    }
    if (pid == 0) {
        sender_loop(sock_fd, (struct sockaddr *)peer);
    } else {
        receive_loop(sock_fd, (struct sockaddr *)peer);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

您的第二个实例在bind()上失败,因为它正在尝试绑定到第一个实例已在使用的端口。

更改为此并查看。

int ret = bind(sock_fd, (struct sockaddr *)peer, sizeof(struct sockaddr_in));
if (ret < 0)
{
    perror("bind");
    exit(1);
}