簡體   English   中英

您可以選擇哪個子進程接收來自父進程的消息嗎?

[英]Can you choose which child process receives a message from a parent?

下面我有一個父進程的代碼,它創建了兩個屬於它的子進程。 現在,我知道我可以這樣做,以便父進程可以寫入子進程,子進程可以使用 read() 和 write() 從中讀取。

我的問題是,父母是否可以在下面的代碼中選擇要寫給哪個孩子? 例如,我問程序的用戶是否想用他們自己提供的消息寫入子進程 1 或子進程 2,我該怎么做?

int p1[2];
int p2[2];
pid_t child_a, child_b;

 if(pipe(p1) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

    if(pipe(p2) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

child_a = fork();

if (child_a == 0) {
    /* Child A code */
} else {
    child_b = fork();

    if (child_b == 0) {
        /* Child B code */
    } else {
        /* Parent Code */
    }
}

您已經創建了兩個管道,因此您走在正確的軌道上。 您可以使用一個管道,例如p1 ,將消息從父級發送到child_a ,並使用p2將消息發送到child_b

您可以使用dup2切換標准輸入文件描述符

int p1[2];
int p2[2];
pid_t child_a, child_b;

 if(pipe(p1) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

    if(pipe(p2) == -1){
        printf("error in creating pipe\n");
        exit(-1);
    }

child_a = fork();

if (child_a == 0) {
    /* Child A code */
    // now can read from stdin to receive messages from parent process
    dup2(p1[0], STDIN_FILENO); 
    // don't forget to close file descriptors that are open in every process!
    close(p1[0]); close(p1[1]);
} else {
    child_b = fork();

    if (child_b == 0) {
        /* Child B code */
        dup2(p2[0], STDIN_FILENO); 
        close(p2[0]); close(p2[1]); 
    } else {
        /* Parent Code */
        // Write something to child A
        write(p1[1], some_text, num_bytes);
        // Write something to child B
        write(p2[1], some_other_text, num_other_bytes);
    }
}

請記住, write需要一個int文件描述符,一個要寫入的void*緩沖區——它可以是一個char* ,以及一個要寫入文件描述符的int字節數。

這是 POSIX API 的write文檔: https : //linux.die.net/man/2/write

這是dup2的文檔: https : dup2

暫無
暫無

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

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