我处于一个必须编写一个创建两个进程的程序的场景中。父亲过程 打开一个文本文件以供阅读。假定文件由以下单词组成: 用空格分隔的字母字符。子进程在键盘上输入一个单词。的 父进程在文件中查找单词,如果单词在 文件,否则为0。儿子显示结果。
在这里,我认为使用这些管道在这些过程之间进行通信。 但是,这种交流对我来说似乎很困难。 请问以下顺序: 处理父进程子进程父进程子进程是可能的吗?
答案 0 :(得分:0)
附加一个简单的管道程序以进行基本了解。可以根据自己的需要进行修改。
/* simple_pipe.c
Simple demonstration of the use of a pipe to communicate
between a parent and a child process.
Usage: simple_pipe "string"
The program creates a pipe, and then calls fork() to create a child process.
After the fork(), the parent writes the string given on the command line
to the pipe, and the child uses a loop to read data from the pipe and
print it on standard output.
*/
#include <sys/wait.h>
#include "tlpi_hdr.h"
#define BUF_SIZE 10
int
main(int argc, char *argv[])
{
int pfd[2]; /* Pipe file descriptors */
char buf[BUF_SIZE];
ssize_t numRead;
if (argc != 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s string\n", argv[0]);
if (pipe(pfd) == -1) /* Create the pipe */
errExit("pipe");
switch (fork()) {
case -1:
errExit("fork");
case 0: /* Child - reads from pipe */
if (close(pfd[1]) == -1) /* Write end is unused */
errExit("close - child");
for (;;) { /* Read data from pipe, echo on stdout */
numRead = read(pfd[0], buf, BUF_SIZE);
if (numRead == -1)
errExit("read");
if (numRead == 0)
break; /* End-of-file */
if (write(STDOUT_FILENO, buf, numRead) != numRead)
fatal("child - partial/failed write");
}
write(STDOUT_FILENO, "\n", 1);
if (close(pfd[0]) == -1)
errExit("close");
_exit(EXIT_SUCCESS);
default: /* Parent - writes to pipe */
if (close(pfd[0]) == -1) /* Read end is unused */
errExit("close - parent");
if (write(pfd[1], argv[1], strlen(argv[1])) != strlen(argv[1]))
fatal("parent - partial/failed write");
if (close(pfd[1]) == -1) /* Child will see EOF */
errExit("close");
wait(NULL); /* Wait for child to finish */
exit(EXIT_SUCCESS);
}
}
在第44章The Linux Programming Interface上查看更多示例。 将此书放在桌上或计算机上的电子书上,这是Linux编程的圣经。