gpt4 book ai didi

子进程和父进程之间的通信

转载 作者:行者123 更新时间:2023-11-30 14:50:13 30 4
gpt4 key购买 nike

我正在尝试在两个进程之间进行通信,一个发送指令的父进程和一个返回响应的子进程。

    void create_player(Game *g, Player *p, int player, char* command) {

int send[2];
int receive[2];
int file;

if(pipe(send)!=0) {
_exit(99);
}
if(pipe(receive)!=0) {
_exit(99);
}

g->player[player].id = fork();

if(g->player[player].id < 0) {
fprintf(stderr, "Unable to start subprocess\n");
fflush(stderr);
exit(5);
}

//Parent process
else if(g->player[player].id>0) {
g->player[player].send = fdopen(send[1], "w");
g->player[player].receive = fdopen(receive[0], "r");

close(send[0]);
close(receive[1]);

//Child process
} else {

close(send[1]);
close(receive[0]);
dup2(send[0], 0);
dup2(receive[1], 1);
close(send[0]);
close(receive[1]);

file = open("/dev/null", O_WRONLY);

for(i =0; i < player; i++) {
fclose(g->player[i].send);
fclose(g->player[i].receive);
}

char width[1024];
char playerId[26];
char numOfPlayers[26];
char seed[1024];
char numOfCarriages[1024];

sprintf(seed, "%d", g->seed);
sprintf(width, "%d", g->numOfCarriages);
sprintf(playerId, "%d", player);
sprintf(numOfPlayers, "%d", g->numOfPlayers);

char* args[] = {command, numOfPlayers, playerId, width, seed, NULL};

execlp(command, command, numOfPlayers, playerId, width, seed, (char*) 0);

_exit(99);

}

当我运行代码块来创建子进程时,没有任何消息通过(父标准输出 -> 子标准输入)发送。我添加了一些示例来展示我如何处理消息传递。任何帮助将不胜感激。

在父进程中:父进程向子进程发送消息

//Send message to start the game
void send_startGame(Game *g) {
fprintf(g->player[g->currentPlayer].send, "startGame\n");
fflush(g->player[g->currentPlayer].send);
}

在子进程中:子消息接收来自父进程的消息

void read_message(Game *g) {
char message[2048];

if(fgets(message, 2048, stdin) == NULL) {
fprintf(stderr, "Error in message\n");
}

//Receive start game message
if(strncmp("startGame\n", message, 9)==0){
start_game(g);
}

}

最佳答案

尝试减少你的代码,子代码中有错误的关闭:

       close(send[1]);
dup2(send[0], 0);
close(send[0]);

在 dup2 之后,文件描述符 send[0] 不再与发送管道输入相关,并且它可能会意外关闭子进程中的其他文件描述符。

您的代码不会从父级的标准输出到子级的标准输入进行通信。下面是一个小示例,将父级的标准输出重定向到管道的输入,并将管道的输出重定向到子级的标准输入。

#include <stdio.h>
#include <unistd.h>

int main(int argc, char **argv) {
int send[2];
if(pipe(send)!=0) {
perror("pipe");
} else {
int pid = fork();
if(pid < 0) {
perror("fork");
}
else if(pid>0) {
//Parent process
close(send[0]); // close pipe input
dup2(send[1], 1); // replace stdout with pipe output

// send message to child
fprintf(stdout, "send to child\n");
fflush(stdout);
} else {
//Child process
close(send[1]); // close pipe output
dup2(send[0], 0); // replace stdin with pipe input

char message[2048];
if(fgets(message, 2048, stdin) != NULL) {
fprintf(stderr, "message from parent:%s", message);
}
}
}
}

Ideone link

关于子进程和父进程之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49093873/

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