C 传递到管道中的未初始化数组(2)
我在手册页上查看如何使用管道(2),但我不理解他们提供的源代码中的一行C 传递到管道中的未初始化数组(2),c,operating-system,system-calls,C,Operating System,System Calls,我在手册页上查看如何使用管道(2),但我不理解他们提供的源代码中的一行 int main(int argc, char *argv[]) { int pipefd[2]; //Isn't this undefined??? so pipe(pipefd) would throw an error? pid_t cpid; char buf; if (argc != 2) { fprintf(stde
int
main(int argc, char *argv[])
{
int pipefd[2]; //Isn't this undefined??? so pipe(pipefd) would throw an error?
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child reads from pipe */
close(pipefd[1]); /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "\n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else { /* Parent writes argv[1] to pipe */
close(pipefd[0]); /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]); /* Reader will see EOF */
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}
int
main(int argc,char*argv[])
{
int pipefd[2];//这不是未定义的吗???所以管道(pipefd)会抛出一个错误?
pid_t cpid;
焦炉;
如果(argc!=2){
fprintf(stderr,“用法:%s\n”,argv[0]);
退出(退出失败);
}
如果(管道(管道FD)=-1){
佩罗(“管道”);
退出(退出失败);
}
cpid=fork();
如果(cpid==-1){
佩罗尔(“福克”);
退出(退出失败);
}
如果(cpid==0){/*子级从管道读取*/
关闭(pipefd[1]);/*关闭未使用的写入端*/
while(读取(pipefd[0],&buf,1)>0)
写入(STDOUT_文件号和buf,1);
写入(标准输出文件号,“\n”,1);
关闭(pipefd[0]);
_退出(退出成功);
}else{/*父对象将argv[1]写入管道*/
关闭(pipefd[0]);/*关闭未使用的读取端*/
写入(pipefd[1],argv[1],strlen(argv[1]);
关闭(pipefd[1]);/*读卡器将看到EOF*/
等待(NULL);/*等待子项*/
退出(退出成功);
}
}
我以为非静态函数变量就是内存中的变量?这个源代码为什么工作?
pipefd
数组在这里用作输出参数,所以不需要初始化它<代码>管道函数将写入其中。数组管道FD返回2个指向管道末端的FD。这里,pipefd[1]表示管道的写入端,pipefd[0]表示管道的读取端
在上述计划中:
还要注意的是,由于管道是单向的,写入管道的写入端(pipefd[1])的数据由内核缓冲,直到从管道的读取端(pipefd[0])读取为止。欢迎使用堆栈溢出-尽管您以前问过问题。请注意,在这里说“谢谢”的首选方式是投票选出好的问题和有用的答案(一旦你有足够的声誉这么做),并接受对你提出的任何问题最有用的答案(这也会给你的声誉带来一点提升)。请参阅本页,以及