c語言管道
A. 利用c語言寫一個程序實現兩個進程間進行管道通信
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#define N 10
#define MAX 100
int child_read_pipe(int fd)
{
char buf[N];
int n = 0;
while(1)
{
n = read(fd,buf,sizeof(buf));
buf[n] = '\0';
printf("Read %d bytes : %s.\n",n,buf);
if(strncmp(buf,"quit",4) == 0)
break;
}
return 0;
}
int father_write_pipe(int fd)
{
char buf[MAX] = {0};
while(1)
{
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1] = '\0';
write(fd,buf,strlen(buf));
usleep(500);
if(strncmp(buf,"quit",4) == 0)
break;
}
return 0;
}
int main()
{
int pid;
int fd[2];
if(pipe(fd) < 0)
{
perror("Fail to pipe");
exit(EXIT_FAILURE);
}
if((pid = fork()) < 0)
{
perror("Fail to fork");
exit(EXIT_FAILURE);
}else if(pid == 0){
close(fd[1]);
child_read_pipe(fd[0]);
}else{
close(fd[0]);
father_write_pipe(fd[1]);
}
exit(EXIT_SUCCESS);
}
B. c語言管道通信能向管道中輸入int型變數嗎
普通管道就可以
只要發送和接收約定好就行
寫的時候sizeof int寫進去
讀的時候同樣讀到int變數就好
C. C語言創建管道
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main(int argc,char *argv[])
{
int pd[2];/*用於保存管道文件描述符*/
char out[80],str[]="safasfsa";/*str是要寫入的字元串,out用於保存從管道讀取的字元串*/
assert(pipe(pd)!=-1);/*斷言用於確定pipe()函數執行成功,如果管道創建失敗,則pipe()返回-1*/
if (!fork()) write(pd[1],str,strlen(str));/*創建子進程,並將字元串寫入管道*/
else {
read(pd[0],out,strlen(str));/*在主進程中從管道中讀取子進程寫入的字元串*/
printf("%s\n",out);/*主進程中輸出。*/
}
return 0;
}
D. C語言 命名管道
先准備好數據比如data.txt 然後編譯好源代碼,得到a.exe 吧兩個文件放在同一個目錄下, 在該目錄下運行命令行 輸入: a << data.txt 回車 就可以了
希望對你能有所幫助。
E. C語言,輸油管道問題
#include<stdio.h>
#include<unistd.h>
#include<string.h>
intmain(intargc,constchar*argv[])
{
intfd[2];
intpid;
if(argc!=2)
{
printf("Usage: %sstring ",argv[0]);
return1;
}
if(pipe(fd)<0)
{
printf("Unabletocreatepipe! ");
return1;
}
//forkchildprocess
pid=fork();
if(pid==0)//child
{
close(fd[0]);//closereadend
write(fd[1],argv[1],strlen(argv[1]));//writemessage
close(fd[1]);//closebeforeexit
}
elseif(pid>0)//parent
{
charbuf[1024];
intlen;
close(fd[1]);//closewriteend
len=read(fd[0],buf,sizeof(buf));//readfromthepipe
buf[len]='