gpt4 book ai didi

c - 在 C 中的两个 indexpendent 进程之间共享数据

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

如何在两个独立(无分支)进程之间共享数据(结构)。我想做的基本上是这样的:

process1:

Server(PID-399341): Waiting for input....

然后在另一个终端

process2:

Enter server process:

399341

Enter a string:

Hello

最后

process1:

"Hello" has been entered.

系统是 QNX/POSIX。我有什么选择可以做到这一点?

谢谢!

最佳答案

使用命名管道(FIFO)可以轻松实现。只需选择与您的 PID 相同的 FIFO 名称。这是服务器和客户端的工作代码。

服务器.c

    int fd;
char buf[10], rdbuf[50];

sprintf(buf,"%d",getpid());

if(mkfifo(buf,0660) == -1)
perror("mkfifo");

printf("Server(PID-%d): Waiting for input..\n",getpid());

fd = open(buf,O_RDONLY);

read(fd, rdbuf, 50);

printf("%s has been entered\n",rdbuf);

close(fd);

return 0;

客户端.c

    int fd;
char wrbuf[50], buf[10];

printf("Enter server process: ");
scanf("%s",buf);
getchar();

fd = open(buf,O_WRONLY);

printf("Enter message\n");

gets(wrbuf);

write(fd, wrbuf, strlen(wrbuf)+1);

我认为可以通过使键值与 PID 相同来对消息队列和共享内存段完成同样的操作。但我不确定。

关于c - 在 C 中的两个 indexpendent 进程之间共享数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39983643/

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