[英]UNIX FIFO: the process hangs if I don't close the input side of the fifo
我剛開始使用UNIX FIFO,在嘗試第一個FIFO程序時發現了一些東西。 該程序以這種方式工作:創建FIFO后,使用fork()
函數啟動兩個進程。 子進程讀取父親通過FIFO傳遞給他的內容,並將其打印在屏幕上。 交換的數據是指定為參數的字符串。 問題是:在父親部分,如果我忘記關閉FIFO的輸入端(這意味着我排除了close(fd)
行),則即使進程之間的數據正確交換,程序也只會掛起。 否則,一切正常,程序將終止且不會掛起。 有人可以解釋一下為什么嗎?
謝謝你的耐心。 這是主要功能的代碼:
int main(int argc, char *argv[])
{
if(argc != 2)
{
printf("An argument must be specified\n");
return -1;
}
int ret = mkfifo("./fifo.txt", 0644);
char buf;
if(ret < 0)
{
perror("Error creating FIFO");
return -1;
}
pid_t pid = fork();
if(pid < 0)
{
perror("Error creating child process");
return -1;
}
if(pid == 0) /* child */
{
int fd = open("./fifo.txt", O_RDONLY); /* opens the fifo in reading mode */
while(read(fd, &buf, 1) > 0)
{
write(STDOUT_FILENO, &buf, 1);
}
write(STDOUT_FILENO, "\n", 1);
close(fd);
return 0;
}
else /* father */
{
int fd = open("./fifo.txt", O_WRONLY); /* opens the fifo in writing mode */
write(fd, argv[1], strlen(argv[1]));
close(fd);
waitpid(pid, NULL, 0);
return 0;
}
}
read(2)
阻塞,直到有可用字符或通道另一端關閉為止。 父進程必須關閉管道,以便最后一個子read()
返回。 如果在父級中省略close(fd)
,則子級將阻塞read()
直到父級退出(自動關閉管道),但父級將掛在waitpid()
直到子級退出。
首先,您發布的代碼存在多個問題。
#include
指令,因此您調用的任何函數的范圍內都沒有原型。 C89需要可變參數的原型,例如printf()
; C99需要所有功能的原型。 無論C89和C99要求的范圍進行報關O_RDONLY
, O_WRONLY
, STDOUT_FILENO
和NULL
。 -1
不是main()
的允許返回值。 小調:通常的稱呼是“父母和孩子”,而不是“父親和孩子”。
我已經修改了您的程序,以解決此問題並提高可讀性:
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
int
main(int argc, char *argv[])
{
if (argc != 2) {
printf("An argument must be specified\n");
return 1;
}
int ret = mkfifo("./fifo.txt", 0644);
char buf;
if (ret < 0) {
perror("Error creating FIFO");
return 1;
}
pid_t pid = fork();
if (pid < 0) {
perror("Error creating child process");
return 1;
}
if (pid == 0) { /* child */
int fd = open("./fifo.txt", O_RDONLY); /* opens the fifo in reading mode */
while(read(fd, &buf, 1) > 0) {
write(STDOUT_FILENO, &buf, 1);
}
write(STDOUT_FILENO, "\n", 1);
close(fd);
return 0;
} else { /* parent */
int fd = open("./fifo.txt", O_WRONLY); /* opens the fifo in writing mode */
write(fd, argv[1], strlen(argv[1]));
close(fd);
waitpid(pid, NULL, 0);
return 0;
}
}
但最重要的是,您沒有提到要使用的操作系統和編譯器。
我無法重現該問題,並且我懷疑它可能與上述問題之一有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.