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]='