パイプを使って親と子の間で通信するために作りたいフォークを持つプログラムを作ろうとしていますが、中央の関数1つは親に、もう1つは子供向け)、通信はそれらを介してのみ行われ、パイプの終了は変数として与えられません。
以下のコードで見られるように、function_managerという関数とmessage_to_father(char * s)という関数があります。私は、function_managerのすべての関数が、それぞれのパラメータとしてパイプの「終了」端を送信する必要なしにmessage_to_fatherを使用できるようにして、そのパラメータでmessage_to_fatherを呼び出します。 message_to_fatherにパラメータなしでパイプを使うことを知らせる方法はありますか?Cの中心関数でパイプを管理する
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <string.h>
//son
void message_to_father(char *s){
// write(out, s, 19);
}
/*
//version that I don't want
void message_to_father(int out, char *s){
// write(out, s, 19);
}
*/
void function_manager(int in, int out){
//function_1(p1, p2, ...) //This would be better
//function_2(out, p1, p2) // I don't want like this
//function_3()
}
//parent
void message_to_son(char *s){
// write(out, s, 19);
}
void user_interface_manager(int in, int out){
}
void initialize(){
int pipe_father_to_son[2], pipe_son_to_father[2];
pid_t pid;
pipe (pipe_father_to_son);
pipe (pipe_son_to_father);
pid = fork();
switch (pid) {
case -1:
perror("fork()");
exit(1);
break;
case 0:
close(pipe_father_to_son[1]);
close(pipe_son_to_father[0]);
function_manager(pipe_father_to_son[0], pipe_son_to_father[1]);
close(pipe_father_to_son[0]);
close(pipe_son_to_father[1]);
break;
default:
close(pipe_father_to_son[0]);
close(pipe_son_to_father[1]);
user_interface_manager(pipe_son_to_father[0], pipe_father_to_son[1]);
close(pipe_father_to_son[1]);
close(pipe_son_to_father[0]);
wait(NULL);
}
}
int main (int argc, char *argv[])
{
initialize();
return 0;
}
あなたの後ろには本当に明確ではありませんが、関数に情報を伝えるためにグローバル変数を使用することはできません。あなたがそれについて考えるならば、 'stdin'と' stdout'は必要に応じて利用できるグローバル変数です。多分これはあなたがこのコードのために必要なものです。しかし、I/Oチャネルを関数に渡して、適切に仕事をすることに抵抗するのはなぜですか?別のオプションは 'dup2()'を使ってチャネルを標準I/Oチャネルにマッピングすることです。それも動作します。 –
ありがとう、dup2のメソッドは、私が使用したものであり、うまく動作します。 –