[英]Writing and reading multiple times on same pipe?
我目前正在查看以下代碼,以在C中使用Pipes:
/*****************************************************************************
Excerpt from "Linux Programmer's Guide - Chapter 6"
(C)opyright 1994-1995, Scott Burkett
*****************************************************************************
MODULE: pipe.c
*****************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
此代碼僅一次將字符串傳輸給父級。 我現在正嘗試向父級發送第二個字符串。 做第二條寫語句(是的,我創建了一個string2):
write(fd[1], string, (strlen(string)+1));
write(fd[1], string2, (strlen(string2)+1));
我還需要做些什么才能使父級注冊第二次寫操作?
謝謝你的幫助
冒明顯的風險,請嘗試:
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
write(fd[1], string, (strlen(string)+1));
// etc.
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
// etc.
也就是說,只寫更多的字符串,更重要的是也閱讀它們! 但是您可能正在問其他問題,因此請澄清您的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.