我不是很清楚管道是如何工作的。对于下面的程序。父进程两次写入管道,子进程两次从管道读取,但在第二次读取时,似乎子进程只读取一个字符。这 程序的输出是:
[2297]:my bufin is {empty}, my bufout is {hello}
[2298]:my bufin is {a}, my bufout is {hello}
为什么子进程的 bufin 是 a 而不是//aaa。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFSIZE 10
int main( void ) {
char bufin[ BUFSIZE ] = "empty";
char bufout[] = "hello";
char b[] = "//aaa";
int bytesin;
pid_t childpid;
int fd[ 2 ];
if ( pipe( fd ) == -1 ) {
perror( "Failed to create the pipe" );
return 1;
}
bytesin = strlen( bufin );
childpid = fork();
if ( childpid == -1 ) {
perror( "Failed to fork" );
return 1;
}
if ( childpid ) { /* parent code */
// Parent node write to the pipe.
write( fd[ 1 ], bufout, strlen( bufout ) + 1 );
write( fd[ 1 ], b, strlen(b) + 1 ); // Just for trying
}
else { /* child code */
bytesin = read( fd[ 0 ], bufin, BUFSIZE );
bytesin = read( fd[ 0 ], bufin, BUFSIZE ); // Just for trying
}
fprintf(stderr, "[%ld]:my bufin is {%.*s}, my bufout is {%s}\n",
(long)getpid(), bytesin, bufin, bufout);
return 0;
}
最佳答案
在第一次读取时,您要求 BUFSIZE 个字节,因此读取得到 'hello\0//aa'(恰好 10 个字符)。当您打印它时,您只会看到“hello”,因为后面有 NULL 字符。只剩下要阅读的字符是一个“a”字母,您会在第二次阅读后看到它。您还忘记了关闭父项和子项中未使用的管道末端。请引用非常好的管道指南:http://beej.us/guide/bgipc/output/html/multipage/pipes.html
关于c - 管道上的多次读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35569943/