传递到管道 (2) 中的未初始化数组
uninitialized array passed into pipe(2)
我正在查看如何在手册页上使用 pipe(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(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);
}
}
我以为非静态函数变量就是内存中的任何东西?为什么此源代码有效?
pipefd
数组在这里作为输出参数,所以不需要初始化它。 pipe
函数 将 写入其中。
Array pipefd returns 2 个指向管道末端的 fds。这里的pipefd[1]指的是管道的写端,pipefd[0]指的是管道的读端。
在上面的程序中:
- pipefd[1] 未在子进程中使用,因此已关闭。 child.
从 pipefd[0] 读取数据
请注意,如果管道为空,则读取阻塞,如果管道已满,则写入阻塞。
- pipefd[0] 未在父级中使用,因此已关闭。 parent.
将数据写入 pipefd[1]
另请注意,由于管道是单向的,写入管道写入端(pipefd[1])的数据由内核缓冲,直到从管道读取端(pipefd[0])读取。
我正在查看如何在手册页上使用 pipe(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(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);
}
}
我以为非静态函数变量就是内存中的任何东西?为什么此源代码有效?
pipefd
数组在这里作为输出参数,所以不需要初始化它。 pipe
函数 将 写入其中。
Array pipefd returns 2 个指向管道末端的 fds。这里的pipefd[1]指的是管道的写端,pipefd[0]指的是管道的读端。
在上面的程序中:
- pipefd[1] 未在子进程中使用,因此已关闭。 child. 从 pipefd[0] 读取数据
请注意,如果管道为空,则读取阻塞,如果管道已满,则写入阻塞。
- pipefd[0] 未在父级中使用,因此已关闭。 parent. 将数据写入 pipefd[1]
另请注意,由于管道是单向的,写入管道写入端(pipefd[1])的数据由内核缓冲,直到从管道读取端(pipefd[0])读取。