gpt4 book ai didi

c - 使用管道发送消息 - C

转载 作者:行者123 更新时间:2023-12-04 10:58:21 26 4
gpt4 key购买 nike

我想做NO_PROC进程,这样每个进程都从其父进程读取消息,然后将这些消息和另一条消息写入其子进程,除非最后一个进程将其消息写入 stdout .所以第 i 个进程将接收 i-1 消息并将发送给子 i 消息。我必须使用管道在进程之间进行通信。我写了代码,但出了点问题,我找不到任何错误:/。当NO_PROC = 5我希望输出看起来像带有“我的消息”的 4 行,但在输出中我有一行:“我的消息”和 3 个空行,就像 3 个消息是空字符串:/。注意,err.h是我的图书馆,它给了我功能syserr()当出现问题时。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include "err.h"

#define NO_PROC 5
#define BUF_SIZE 20

char message[] = "my message";
int parent;
char buf[BUF_SIZE];

int main()
{
for (int i = 0; i < NO_PROC; ++i) {
int pipe_dsc[2], buf_len;
if (pipe(pipe_dsc) == -1)
syserr("Error in pipe\n");
pid_t pid = fork();
if (pid == -1)
syserr("Error in fork\n");
else if (pid == 0)
parent = pipe_dsc[0];
else {
for (int j = 0; j < i; ++j) {
if ((buf_len = read(parent, buf, BUF_SIZE - 1)) == -1)
syserr("Error in read\n");
buf[buf_len < BUF_SIZE - 1 ? buf_len : BUF_SIZE - 1] = '\0';
if (i == NO_PROC - 1)
printf("%s\n", buf);
else if (write(pipe_dsc[1], buf, sizeof(buf)) != sizeof(buf))
syserr("Error in write\n");
}
if (i < NO_PROC - 1 && write(pipe_dsc[1], message, sizeof(message)) != sizeof(message))
syserr("Error in write\n");
if (wait(0) == -1)
syserr("Error in wait\n");
return 0;
}
}
}

最佳答案

我认为您过于复杂化和/或使用了错误的方法。您不必向 i 进程发送 i 消息。由于第 i 个进程是第 i-1 个进程的副本(fork),因此它已经收到了 i-1 条消息,并且只需要一个。这是一个相当对称(和学术)的问题。

这是一个示例(省略了健壮的错误检查)。请注意,这依赖于原子管道写入,只要您不写入大于 PIPE_BUF 的消息就可以了。 (见 man pipe):

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>

void syserr(char * msg) { printf("%s\n", msg); exit(1); }
#define NO_PROC 5
#define BUF_SIZE 100
char message[] = "my message ";

int main() {
int message_len = 0;
char buf[BUF_SIZE];
for (int i = 0; i < NO_PROC; ++i) {
int pipe_dsc[2], buf_len;
if (pipe(pipe_dsc) == -1) {
syserr("Error in pipe\n");
}
pid_t pid = fork();
if (pid == -1) {
syserr("Error in fork\n");
}
else if (pid == 0) {
close(pipe_dsc[1]);
int n = read(pipe_dsc[0], buf+message_len, sizeof(buf));
message_len = strlen(buf); // Assume message is null terminated string.
if(i == NO_PROC -1) {
printf("Process %i: received '%s'\n", i+1, buf);
}
}
else {
close(pipe_dsc[0]);
write(pipe_dsc[1], message, sizeof(message));
wait(0);
return 0;
}
}
}

关于c - 使用管道发送消息 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371502/

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