进程间通信似乎挂了

Posted

技术标签:

【中文标题】进程间通信似乎挂了【英文标题】:Inter-process communication seems to be hanging 【发布时间】:2014-06-02 04:59:51 【问题描述】:

这是一个程序,旨在从程序调用中获取字符,一次将一个字符传递给一个子进程,在子进程中计算它们,将该值返回给父进程并打印该值。 由于某种原因,没有显示输入的字符数。它编译没有错误并运行,但没有正确退出。这让我相信父母没有成功地收获孩子并从中获取返回值。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <string.h>


int main(int argc, char **argv)

    int comm[2];
    char buffer[50];
    pid_t   pid;

    // set up pipe

    pipe(comm);

    // call fork()
    pid = fork();

    // code that runs in the child  
    if (pid == 0) 
        // -- running in child process --
        int     nChars = 0;

        close(comm[1]);

        // Receive characters from parent process via pipe
        // one at a time, and count them.

        while(read(comm[0], buffer, 1) ==1) 
            ++nChars;
        

        // Return number of characters counted to parent process.
        return nChars;
    
    else 
        // -- running in parent process --
        int     nChars = 0;
        int     size = 0;
        printf("CS201 - Assignment 3 - \n");

        // Send characters from command line arguments starting with
        // argv[1] one at a time through pipe to child process.
        close(comm[0]);
        for (int i = 1; i < argc ; i++) 
            size = strlen(argv[i]);
            for (int j = 0; j < size; j++) 
            write(comm[1], &argv[i][j], 1);
                
            

        // Wait for child process to return. Reap child process.
        // Receive number of characters counted via the value
        // returned when the child process is reaped.

        wait(&nChars);
        printf("child counted %d chars\n", nChars/256);
        return 0;
        

【问题讨论】:

【参考方案1】:

你的父进程需要在写完后关闭管道。

// Send characters from command line arguments starting with
// argv[1] one at a time through pipe to child process.
close(comm[0]);
for (int i = 1; i < argc ; i++) 
    size = strlen(argv[i]);
    for (int j = 0; j < size; j++) 
        write(comm[1], &argv[i][j], 1);
    

close(comm[1]); // <--- add this

【讨论】:

非常感谢。完美解决了我的问题。

以上是关于进程间通信似乎挂了的主要内容,如果未能解决你的问题,请参考以下文章

Java Attach API 使用啥进程间通信机制?

Python进程间通信建议

Discord 进程间通信 - 阅读消息

VC++ 进程间的通信

Linux系统编程--进程间通信 ---管道篇

Linux进程间通信——管道