linux c 進程 pipe 通訊程式碼分析,linuxpipe

來源:互聯網
上載者:User

linux c 進程 pipe 通訊程式碼分析,linuxpipe
[root@luozhonghua 04]# cat ex04-3-pipe02.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


int main(void){
   int result=-1;
   int fd[2],nbytes;
   pid_t pid;
   char string[]="hello,pipe";
   char readbuffer[80];


   int *write_fd = &fd[1];  //可寫
   int *read_fd = &fd[0];  //read


   result = pipe(fd);  //create pipe


   if(-1 == result){
     printf("create pipe faile");
     return -1;
    }


   pid=fork(); //分叉程式


   if(-1 == pid){
    printf("fork 進程失敗\n");
    return -1;
   }


   if(0 == pid ){
     close(*read_fd);
     /*向管道端寫入字元*/
     result=write(*write_fd,string,strlen(string));


   }else{
     close(*write_fd);
     /* read pipe data */
     nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));
     printf("接收到%d 個資料,內容:%s \n",nbytes,readbuffer);
     printf("sizeof(readbuffer) =  %d\n",sizeof(readbuffer));
   }


   return 0;

}


--------------測試結果

[root@luozhonghua 04]# ./ex04-3-pipe02
接收到10 個資料,內容:hello,pipe
sizeof(readbuffer) =  80



linux處理序間通訊實驗(管道)原始碼

這個原始碼龐大了,看下《進階環境編程》裡面有這個的代碼實現的
 
linux下C進程之間管道通訊的問題,懂的進來看下這段程式怎運行起來不對

你的要求 “管道尾寫個資料後,管道頭讀,然後在讓管道尾寫,一直迴圈”,其實是一個進程同步的問題,即一邊寫完了,另外一邊讀,讀完了,才能再寫。所以要用到處理序間通訊的方式來讓讀段通知寫端我已經讀完了,你可以寫下一個了。 有很多種方法來實現這個進程同步,比如用訊號量等。不過既然你是一個管道的代碼,我就用了管道的方式來實現,讓你參考。下面的代碼建立了兩個管道,pipe_a2b 這個就是你原來的那個管道, pipe_b2a 這個是新加的,用來讓讀端通知寫端可以繼續的。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

int main()
{
char r_buf[10];
char w_buf[10];
pid_t pid;
int pipe_a2b[2]; /* parent write, child read */
int pipe_b2a[2]; /* child write, parent read */
memset(r_buf,0,sizeof(r_buf));

if(pipe(pipe_a2b)<0)
{
printf("creat pipe error\n");
exit(1);
}
if(pipe(pipe_b2a)<0)
{
printf("creat pipe error\n");
exit(1);
}

pid=fork();

if (pid == 0)
{
/* child, reader */
close(pipe_a2b[1]);
close(pipe_b2a[0]);
while(1)
{
read(pipe_a2b[0],r_buf,10);
printf("FIFO :%s\n",r_buf);
write(pipe_b2a[1], "c", 1); /* tells parent continue */
}
close(pipe_a2b[0]);
close(pipe_b2a[1]);
}

if(pid>0)
{
/* parent, writer */
close(pipe_a2b[0]);
close(pipe_b2a[1]);
while(1)
{
printf("please input w_buf:\n");
scanf("%s",w_buf);
write(pipe_a2b[1],w_buf,strlen(w_buf));

/* wait for the "c" from child to continue to next write */
read(pipe_b2a[0], r_buf, 10);
}......餘下全文>>
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.