簡體   English   中英

為什么這段代碼打到管道時會停止運行?

[英]Why does this code stop running when it hits the pipe?

該程序運行時,它將在父級中循環,然后在寫入管道時切換到子級。 在子進程中,讀取的管道正好導致程序停止。

當前示例輸出:

父級4741 14087(僅當預期還有5行時才是此行)

預期輸出(帶有隨機生成的數字):

父母4741 14087

兒童4740 47082

父母4741 11345

兒童4740 99017

父母4741 96744

子級4740 98653(當給定變量3並且最后一個數字是隨機生成的數字時)

#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <time.h>
#include <ctime>
using namespace std;

int main (int argc, char *argv[]) {
    int pid = fork(), temp, randNum, count, pipeName[2], pipeName2[2];
    string conver;
    pipe(pipeName);
    conver = argv[1];
    temp = atoi(conver.c_str());
    char letter;


    if (pid == 0) { //child
        srand((unsigned)time(NULL) * getpid() );
        //closing unused pipes
        close(pipeName2[1]);
        close(pipeName[0]);
        //loop to switch between processes
        for(int i=0; i<temp; i++) {
            count = read(pipeName2[0], &letter, 20);
            randNum = rand();
            cout << "Child " << getpid() << " " << randNum << endl;
            write(pipeName[1], "x", 1);
        }
        close(pipeName2[0]);
        close(pipeName[1]);
    }
    else { //parent
        srand((unsigned)time(NULL) * getpid() );
        pipe(pipeName2);
        //closing unused pipes
        close(pipeName2[0]);
        close(pipeName[1]);
        //loop to switch between processes
        for(int i=0; i<temp; i++) {
            if(i != 0)
                count = read(pipeName[0], &letter, 20);
            randNum = rand();
            cout << "Parent " << getpid() << " " << randNum << endl;
            write(pipeName2[1], "x", 1);
        }
        close(pipeName[0]);
        close(pipeName2[1]);
    }
}

該程序在擊中子管道中的讀取內容時結束。

您的主要錯誤是在初始化管道之前執行fork() 因此,父級和子級都有它們自己的專用管道對(不通過fd繼承共享),它們的管道對名為pipeName ,只有父級對才使用管道fds初始化pipeName2

對於父級,在pipeName[0]后面根本沒有數據可讀取。 對於孩子……誰知道它在pipeName2[1]寫入什么fd? 如果您很幸運,使用EBADF失敗。

因此,先進行兩次pipe()然后進行 fork() ,看看是否可以改善。

暫無
暫無

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

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