[英]C:pipe How to write data multiple time on same pipe?
//child process
char buf[20];
read(fd[0][0], buf, 20);
printf("%s", buf);
//parent process
write(fd[0][1], "12", 20);
write(fd[0][1], "14", 20);
write(fd[0][1], "15", 20);
--output--
12
//then the program just exit. It cannot print out 14 and 15.
我可以知道如何解決這個問題嗎? 我可以讓子進程一直等到它真正從管道中讀取數據嗎?
我編輯了程序。 並且它可以讀取所有數據。 但是,該程序只是停止。 它無法繼續處理。 我認為它停止在子進程中。
//child process
buf[6];
int i;
while ((i = read(fd[0][0], buf, 6)) > 0) {
printf("%s", buf);
}
//parent process
write(fd[0][1], "12", 2);
write(fd[0][1], "14", 2);
write(fd[0][1], "15", 2);
printf("done!\n");
--output--
121415done
//The program just stopped in child process.
static const int BUF_SIZE = 4;
char buf[BUF_SIZE];
ssize_t read_bytes;
int i;
while ((read_bytes = read(fd[0][0], buf, BUF_SIZE)) > 0) {
printf("BUF: {\n'");
for (i = 0; i < read_bytes; ++i) {
if (buf[i] != '\0')
putchar(buf[i]);
}
printf("'\n} : EOBUF[%d]\n", nbytes);
}
if (read_bytes < 0) {
perror("FAIL");
}
編輯:如果寫入大小大於>寫入數據,則效果不佳。 垃圾結束。
它確實從管道讀取了數據。 您說“最多讀取20個字節”,它確實做到了(請注意,它也有17個垃圾字節,並且您的父進程正在讀取3字節緩沖區的末尾,試圖發送它們!)。 如果希望它讀取更多字節,請再次調用read()。
read
將讀取最多您指定的字節數。 它讀起來可能更少:這一切都取決於緩沖。 為了確保獲得所需的字節數,必須在循環中使用read
:
//child process
#define MAXLEN 20
int total_read = 0, n;
char buf[MAXLEN + 1];
buf[MAXLEN] = 0;
p = buf;
while (total_read < MAXLEN) {
n = read(fd[0][0], p, MAXLEN - total_read);
if (n < 0)
break; //error
if (n == 0)
break; //end of file
total_read += n;
p += n;
}
printf("%s", buf);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.