溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

[Linux管道和IPC]在兄弟進程中使用管道

發(fā)布時間:2020-07-15 16:11:21 來源:網(wǎng)絡(luò) 閱讀:303 作者:銀河星君 欄目:編程語言
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <limits.h>
#include <string.h>
#include <errno.h>
#define BUFSIZE 4096  //定義一個最大的讀寫空間
int main(void)
{
    int fd[2];
    char buf[BUFSIZE] = "hello!I am your  brother!\n";        // 緩沖區(qū)
    pid_t pid;
    int len;
    if ( (pipe(fd)) < 0 )           //創(chuàng)建管道
     {
        perror("pipe failed\n");
     }
    if ( (pid = fork()) < 0 )        //創(chuàng)建第一個子進程
     {
        perror("fork failed\n");
     }
    else if ( pid == 0 )            //子進程
    {
        close ( fd[0] );                //關(guān)閉不使用的文件描述符
        write(fd[1], buf, strlen(buf));   //發(fā)送字符串
        exit(0);
     }
    if ( (pid = fork()) < 0 )             //創(chuàng)建第二個子進程
     {
        perror("fork failed\n");
     }
    else if ( pid > 0 )             //父進程
    {
        close ( fd[0] );
        close ( fd[1] );
        exit ( 0 );
     }
    else                       //第二個子進程中
    {
        close ( fd[1] );                  //關(guān)閉管道文件描述符
        len = read (fd[0], buf, BUFSIZE);  //讀取消息
        write(STDOUT_FILENO, buf, len); //將消息輸出到標準輸出
        exit(0);
     }
    return 0;
}


向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI