IPC をよりよく理解するために書いている単純な Linux C プログラムがあります。現在、パイプを使用してビルドしようとしています。
2 つの異なるターミナル ウィンドウで 2 つの異なる実行可能ファイルとして実行する単一のコード ベースがあります (相互に通信できるようにするため)。ただし、データを読み取ることができないため、正しいことをしていませんが、何がわからない...
注: これは完全なコードではありません。スペースを節約するために、出力/入力/検証を切り取っています。しかし、それは以下のプログラムのコメントに記載されています。
void main()
{
int pipefd[2], n;
char input = 0;
char buffer[100] = {0};
char outpipe[100] = {0};
if(pipe(pipefd) < 0) {
printf("FAILED TO MAKE PIPES\n");
return;
}
printf("Starting up, read fd = %d, write fd = %d\n", pipefd[0],pipefd[1]);
do {
//print menu options (send message, get message, get my fd,
// set a fd to talk to, quit)
// if "send a message":
{
printf("What would you like to send?\n");
fgets(buffer, 100, stdin);
write(pipefd[1], buffer, strlen(buffer));
}
//else if "read a message":
{
if(open(outpipe, 0) < 0)
printf("Couldn't open the pipe!\n");
else {
n = read(outpipe, buffer, 100);
printf("I got a read of %d bytes\nIt was %s\n",n, buffer);
close(outpipe);
}
}
//else if "get my file descriptor":
printf("My fd tag is: /proc/%d/fd/%d\n", (int)getpid(), pipefd[0]);
//else if "set a file descriptor to talk to":
{
printf("What is the pipe's file descriptor?\n");
fgets(outpipe, 100, stdin);
n = strlen(outpipe) - 1;
outpipe[n] = '\0';
}
} while (input != 'Q');
return;
}
パイプが正常に作成されたことはわかっています。ファイル記述子が配置されていることを確認しました。
lr-x------ 1 mike users 64 Sep 26 23:31 3 -> pipe:[33443]
l-wx------ 1 mike users 64 Sep 26 23:31 4 -> pipe:[33443]
権限は問題ないようです (パイプ 3 で読み取り、パイプ 4 で書き込み)。
私はそれを次のように使用します:
//terminal 1
Pick an option:
3
My fd tag is: /proc/8956/fd/3
//terminal 2
Pick an option:
4
What is the pipe's file descriptor?
/proc/8956/fd/3
Pick an option:
1
What would you like to send?
hello
//terminal 1
Pick an option:
2
I got a read of -1 bytes
It was
私がここでやっていることは明らかに間違っていますか?私の読み取りは常に「-1」の戻り値を取得します...