首页 > 解决方案 > 进程间通信与c中的数据发送

问题描述

我在一个场景中,我必须编写一个创建两个进程的程序。父进程打开一个文本文件供阅读。假定该文件由由空格分隔的字母字符组成的单词组成。子进程在键盘上输入一个单词。父进程在文件中查找单词,如果单词在文件中,则将值 1 传递给子进程,否则将值传递给 0。儿子展示了结果。

在这里,我认为使用管道在这些进程之间进行通信。但是,在我看来,这种沟通很困难。这个顺序:进程父进程子进程父进程子是可能的吗?

标签: cposix

解决方案


附上一个简单的管道程序以供基本理解。可以根据自己的需要进行修改。

/* 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 章Linux 编程接口上查看更多示例。把这本书放在你的桌子上或电子书放在你的电脑上,它是 Linux 编程的圣经。


推荐阅读