gpt4 book ai didi

c - fork 进程与套接字通信

转载 作者:太空宇宙 更新时间:2023-11-04 01:05:20 25 4
gpt4 key购买 nike

我正在尝试创建一个套接字,该套接字与两个已 fork 的子进程 a 和 b 进行通信。我需要它通过套接字 sc 进行通信。作为起点,我试图让进程 a 通过 sc 套接字向进程 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;
}

我不断收到“错误绑定(bind)”和“错误接受”消息 - 再次感谢您。

最佳答案

来自 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;
}

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

关于c - fork 进程与套接字通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24623203/

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