我正在编写一个程序,其中父进程使用fork()创建N子进程(将N作为参数提供),以便每个子进程都直接由这个父进程派生.
I am writing a program in which the parent process uses fork() to create N child processes (N is provided as an argument), so that every child is directly forked by this one parent.
每个子进程都需要从stdin中读取一行,并打印到屏幕上. 编译并执行程序后,将通过以下文本文件提供文本:
Every child process needs to read a line from stdin, and print on to the screen. After compiling and executing the program, the text is provided through a text file like this:
./prog1 3 < fileWithText.txt
我的问题是,我希望看到每个孩子都在为阅读输入而打架",但是我实际上看到的是,总是只有一个子进程负责处理输入.这是我用于子进程的代码:
My problem is, that I am expecting to see every child "fight" for reading the input, however what I actually see is that there is always only one child process taking care of handling the input. This is the code I use for the child process:
void do_child_reader(int j) { int pid; int counter = 0; char* buffer; char* readCheck; int readerRunning = TRUE; pid = getpid(); buffer = (char*)malloc(BUFFER_SIZE * sizeof(char)); while (readerRunning == TRUE) { readCheck = fgets(buffer, BUFFER_SIZE, stdin); if (readCheck == NULL) { readerRunning = FALSE; } else { fprintf(stdout, "(READER %d pid-%d) %s", j, pid, buffer); counter++; } } fprintf(stderr, "(READER %d pid-%d) processed %d messages, going to exit\n", j, pid, counter); free(buffer); exit(counter); }这是我在运行N = 3时得到的输出:
Here's the output I get when running for N=3:
(READER 0 pid-72655) I am a message - line 1 (READER 0 pid-72655) I am a message - line 2 (READER 0 pid-72655) I am a message - line 3 (READER 0 pid-72655) processed 3 messages, going to exit (READER 1 pid-72657) processed 0 messages, going to exit (READER 2 pid-72659) processed 0 messages, going to exit父进程正在等待子进程完成后退出.
The parent process is waiting for the children to finish before exiting.
我正在尝试找出导致此行为的原因,以及它是通过fgets()的方式还是以我尝试读取字符串的方式.
I am trying to figure out what would cause this behaviour, and whether it is in the way fgets() works or perhaps in the way I am trying to read the strings.
谢谢!
推荐答案如果文件太小,一个进程可以读取一个BUFSIZ字节(来自<stdio.h>)字节,那么其他进程就什么也没剩下读书.增大输入文件的大小(是BUFSIZ大小的倍数),并确保客户机在缓冲区已满后读取速度足够慢,并且您会看到它们都在工作.
If the file is so small that one unit of BUFSIZ (from <stdio.h>) bytes can be read by one process, the other processes have nothing left to read. Make the input file bigger — multiple times the size of BUFSIZ — and make sure the clients read slowly enough after getting a buffer full, and you will see them all working on it.
这是为您提供的I/O缓冲.您可以尝试弄乱setvbuf()来设置输入的行缓冲.我不确定是否可以.
This is I/O buffering for you. You could try messing with setvbuf() to set line buffering on the input; I'm not sure it would work.
更多推荐
通过多个过程从stdin读取
发布评论