簡體   English   中英

進程間通信似乎已停止

[英]Inter-process communication seems to be hanging

這是一個旨在從程序調用中獲取字符,一次將一個字符傳送到一個子項,將它們計入子項中,將其返回給父項並打印該值的程序。 由於某些原因,沒有顯示輸入的字符數。 它可以正確編譯並運行,但是不能正確退出。 這使我相信父級不會成功地收獲子級並從中獲取返回值。

#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;
        }
}

完成編寫后,您的父進程需要關閉管道。

// 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM