サーバークライアントベースのCプログラムを作成しています。
stdin を作成した名前付きパイプにリダイレクトしようとしてきましたが、パイプに書き込むクライアントを置くことができました。サーバー側では、同じパイプを開き、stdin を閉じて、dup (dup2 でも試しました) を使用して stdin をパイプにリダイレクトしました。
関数 getline で入力を読み取る必要があります。問題は、最初の入力を正しく読み取るが、その後は null しか受信しないことです。質問にサンプルを追加します。
サーバ:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
main () {
char* str;
size_t size=0;
int pshell_in;
unlink("/tmp/par-shell-in");
if(mkfifo("/tmp/par-shell-in", 0777) < 0){
fprintf(stderr, "Error: Could not create pipe\n");
exit(-1);
}
if((pshell_in = open("/tmp/par-shell-in", O_CREAT | O_RDONLY, S_IRUSR)) < 0){
fprintf(stderr, "Error: Failed to open file\n");
exit(-1);
}
dup2(pshell_in, 0);
close(pshell_in);
while(1) {
if (getline(&str, &size, stdin)<0) {
printf("Oh dear, something went wrong with getline()! %s\n", strerror(errno));
return -1;
}
printf("%s", str);
}
}
* null の原因はわかっていますが、(リダイレクトではなく) read で出力し、(null) を出力しました。
クライアント:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#define VECTORSIZE 7
int main() {
char* buf;
int pshell_in;
size_t size=0;
if((pshell_in = open("/tmp/par-shell-in", O_WRONLY, S_IWUSR)) < 0){
fprintf(stderr, "Error: Failed to open file\n");
exit(-1);
}
printf("%d\n", pshell_in);
while(1) {
if (getline(&buf, &size, stdin) < 0) {
return -1;
}
write(pshell_in, buf, 256);
}
}
- クライアント側で read を使用すると (O_WRONLY を O_RDWR に置き換える)、入力したとおりに文字列が出力されるため、それが正しいと思われます。
誰でもこれで私を助けることができますか?