Multiprocessing and Pipes in C

后端 未结 3 1187
北海茫月
北海茫月 2021-01-21 08:59

I\'m trying to learn how to work with fork() to create new processes and pipes to communicate with each process. Let\'s say I have a list that contains

3条回答
  •  Happy的楠姐
    2021-01-21 09:18

    The overall picture is usually:

    pid_t pids[3];
    int fd[3][2];
    
    int i;
    for (i = 0; i < 3; ++i) {
        /* create the pipe */
        if (pipe(fd[i]) < 0) {
                perror("pipe error");
                exit(1);
        }
    
       /* fork the child */
       pid[i] = fork();
       if (pid[i] < 0) {
           perror("fork error");
       } else if (pid[i] > 0) {
           /* in parent process */
           /* close reading end */
           close(fd[i][0]);
       } else {
           /* in child process */
           /* close writing end */
           close(fd[i][1]);
           /* read from parent */
           read(fd[i][0], line, max);
           ...
        }
    }
    
    /* in parent process */
    char words[100][10] = {...};
    int j, child = 0;
    /* for all words */
    for (j = 0; j < 100; ++j) {
        /* write to child */
        write(fd[child][1], words[j], strlen(words[j]));
        ...
        ++child;
        if (child >= 3)
            child = 0;
    }
    

    Duplicate the pipe part for communicating back from child to parent. Be careful not to deadlock when parent and child are trying to communicate in both directions simultaneously.

提交回复
热议问题