我正在创建一个带有服务器端客户端的C程序。使用FIFO(名称管道)重定向stdin
我一直在试图将标准输入重定向到我创建的命名管道,并且设法将客户端写入管道。在服务器端,我打开了相同的管道,关闭了stdin,并使用dup(用dup2尝试)将管道重定向到stdin。
我必须使用函数getline读取输入。问题是它会正确读取第一个输入,但在它之后只收到空值。我会在问题中添加一个示例。
服务器:
#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);
}
}
*我知道它的空,因为我已经与读取印刷它(而不是重定向),并将其打印(空)。
客户端:
#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);
}
}
- 我怀疑它的正确的,因为如果我用阅读客户端(与O_RDWR O_WRONLY更换)它打印我键入它的字符串。
任何人都可以帮助我这个吗?