gpt4 book ai didi

c - 传输端点未连接

转载 作者:行者123 更新时间:2023-11-30 16:31:28 24 4
gpt4 key购买 nike

我试图在 fork 后的两个进程之间创建通信,从而在父进程和子进程之间创建通信。我尝试使用 PF_UNIXAF_UNIX 系列的套接字,但是当我尝试发送消息时,出现错误“传输端点未连接”。我真的不明白我的错误在哪里。

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <unistd.h>
#include <netinet/in.h>
#include <netdb.h>
#include <sys/un.h>

#define PATH "/tmp/Server"
int main() {
pid_t proc1, proc2;
proc1 = fork();
if(proc1 == -1) {
printf("Errore nella prima fork\n");
exit(0);
}

if(proc1 != 0) {
//PADRE DOPO IL PRIMO FIGLIO

//Lo stesso procedimento si fa per il secondo figlio
proc2 = fork();
if(proc2 == -1) {
printf("Errore nella prima fork\n");
exit(0);
}
wait(NULL); //Attesa che UN figlio termini
if(proc2 != 0) {
//PADRE DOPO I DUE FIGLI
unlink(PATH);
int father_desc = socket(PF_UNIX, SOCK_STREAM, 0);
int son1_desc;
struct sockaddr_un father_add = {AF_UNIX, PATH};
struct sockaddr_un son1_add;

if(-1 == bind(father_desc, (struct sockaddr*)&father_add, sizeof(struct sockaddr))) {
perror("Errore nel bind");
close(father_desc);
close(son1_desc);
wait(NULL);
exit(0);
}

if(-1 == listen(father_desc, 2)) {
perror("Errore nel listen");
close(father_desc);
close(son1_desc);
wait(NULL);
exit(0);
}

int len = sizeof(son1_add);
son1_desc = accept(father_desc, (struct sockaddr*)&son1_add, &len);
if(-1 == son1_desc) {
perror("Errore nell'accept");
close(father_desc);
close(son1_desc);
wait(NULL);
exit(0);
}

char message[256] = "Ciao";
if(-1 == send(father_desc, message, strlen(message) + 1, 0)) {
perror("Errore nel send"); /* -> ERROR HERE */
close(father_desc);
close(son1_desc);
wait(NULL);
exit(0);
}

close(father_desc);
close(son1_desc);
wait(NULL);
} else {
//SECONDO FIGLIO

}
} else {
//PRIMO FIGLIO
sleep(1);
struct sockaddr_un son1_add = {AF_UNIX, PATH};
int son1_desc = socket(PF_UNIX, SOCK_STREAM, 0);

if(-1 == connect(son1_desc, (struct sockaddr*) &son1_add, sizeof(struct sockaddr))) {
perror("Errore nel connect");
shutdown(son1_desc, SHUT_RDWR);
close(son1_desc);
exit(0);
}

char message[256] = "";
if(-1 == recv(son1_desc, message, strlen(message) + 1, 0)) {
perror("Errore nel rcv");
shutdown(son1_desc, SHUT_RDWR);
close(son1_desc);
wait(NULL);
exit(0);
}

printf("%s\n", message);

shutdown(son1_desc, SHUT_RDWR);
close(son1_desc);
}
return 0;
}

最佳答案

您想在接受的套接字上调用 send,而不是在监听套接字上调用 send。

所以这个

 if(-1 == send(father_desc, message, strlen(message) + 1, 0)) {

应该是

 if(-1 == send(son1_desc, message, strlen(message) + 1, 0)) {

除此之外还有其他问题:

  • len 应该是 socklen_t 而不是 int
  • 客户端无法检查对 socket() 的调用是否成功。
  • strlen() 对空字符串返回 0

关于c - 传输端点未连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50550713/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com