我目前正在查看以下用于在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));
我还需要做些什么来让父母注册第二次写作?
感谢您的帮助
答案 0 :(得分:-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.
也就是说,只需要写更多字符串 AND ,更重要的是阅读它们!?但你可能会问别的,所以请澄清你的问题。