此功能:
char* read_from_pipe()
{
int file = fd[0];
static char buf[100];
FILE *stream;
stream = fdopen(file, "r");
read(file,buf,100);
fclose(stream);
return buf;
}
包含几个问题。
建议写它类似于:
#define MAX_BUF_LEN 100
char* read_from_pipe()
{
static char buf[ MAX_BUF_LEN +1 ];
ssize_t byteCount = read(fd[0], buf, MAX_BUF_LEN);
if(0 > byteCount)
{ // an error occurred
perror("read from pipe failed");
buf[0] = '\0';
}
else if(0 == byteCount)
{
fprintf(stderr, "no bytes read\n");
buf[0] = '\0';
}
else
{
buf[byteCount] = '\0';
}
return buf;
} // end function: read_from_pipe
注:read()
不会终止字符数组,所以代码必须做到这一点,数组必须是1个字符长度超过字符问的最大数量因为在read()
声明中。
注意:read()
的语法需要int
,而不是FILE*
作为其第一个参数。下面是正确的语法:
ssize_t read(int fd, void *buf, size_t count);
此功能:
int fd[2];
void write_to_pipe(char* str)
{
int file = fd[1];
FILE *stream;
//printf("writing to pipe : %s\n", str);
stream = fdopen(file, "w");
//printf("fdopen returned : %d\n",(int)stream);
fprintf(stream, "%s", str);
fclose(stream);
}
极不理想很多。
建议添加类似的东西:
int fd[2]; << in file scope, so visible from functions
void write_to_pipe(char* str)
{
//printf("writing to pipe : %s\n", str);
ssize_t bytesWritten = write(fd[1], str, strlen(str));
if(strlen(str) != bytesWritten)
{
fprintf(stderr, "write to pipe failed to write all bytes\n");
}
else if(0 > bytesWritten)
{
perror("write to pipe failed");
}
} // end function: write_to_pipe
你'read_from_pipe()'有很多比关闭文件描述符更大的问题。你在'FILE *'中调用'read()'。这根本不起作用。 'read()'直接获取一个文件描述符,并且它不会NUL终止它所读取的内容。 –
你应该使用[popen(3)](http://man7.org/linux/man-pages/man3/popen.3.html)和'pclose' –
@BasileStarynkevitch但是'popen()'不会提供一个双向管道。它是只读或只写的。 –