管道

#include <stdio.h>

FILE *popen(const char *command,const char *open_mode);

int pclose(FILE *stream_to_close);

 

 

代码
#include <unistd.h>
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>

int main(void)
{
FILE
*write_fp;
char buffer[BUFSIZ+1];
sprintf(buffer,
"Once upon a time,there was...\n");
write_fp
=popen("od -c","w");
if(write_fp != NULL)
{
fwrite(buffer,
sizeof(char),strlen(buffer),write_fp);
pclose(write_fp);
}
return 0;
}
代码
#include <unistd.h>
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>

int main()
{
FILE
*read_fp;
char buffer[BUFSIZ+1];
int chars_read;
memset(buffer,
'\0',sizeof(buffer));

read_fp
=popen("ps -ax","r");

if(read_fp != NULL)
{
chars_read
=fread(buffer,sizeof(char),BUFSIZ,read_fp);
while(chars_read > 0)
{
buffer[chars_read
-1]='\0';
printf(
"Reading:-\n%s\n",buffer);
chars_read
=fread(buffer,sizeof(char),BUFSIZ,read_fp);
}
}
pclose(read_fp);
return 0;
}

 

读取大量数据:

代码
#include <unistd.h>
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>

int main(void)
{
FILE
*fread_fp;
char buffer[BUFSIZ+1];
int chars_bytes;

fread_fp
=popen("cat popen*.c | wc -l","r");
if(fread_fp != NULL)
{
chars_bytes
=fread(buffer,sizeof(char),BUFSIZ,fread_fp);
while(chars_bytes > 0)
{
buffer[chars_bytes
-1]='\0';
printf(
"\n%s\n",buffer);
chars_bytes
=fread(buffer,sizeof(char),BUFSIZ,fread_fp);
}
pclose(fread_fp);
}
return 0;
}

 

#include <unistd.h>

int pipe(int file_descripter[2]);

基本使用:

代码
#include <unistd.h>
#include
<stdlib.h>
#include
<stdio.h>
#include
<string.h>

int main(void)
{
int data_processed;
int file_pipes[2];
const char some_data[]="123";
char buffer[BUFSIZ+1];
memset(buffer,
'\0',sizeof(buffer));

if(pipe(file_pipes) == 0)
{
data_processed
=write(file_pipes[1],some_data,strlen(some_data));
printf(
"wrote %d bytes\n",data_processed);
data_processed
=read(file_pipes[0],buffer,BUFSIZ);
printf(
"read %d bytes:%s\n",data_processed,buffer);
}
return 0;
}

利用fork调用管道:

代码
#include <unistd.h>
#include
<stdio.h>
#include
<stdlib.h>
#include
<string.h>

int main(void)
{
int file_pipes[2];
int data_processed;
const char some_data[]="1234";
char buffer[BUFSIZ+1];
pid_t fork_result;
memset(buffer,
'\0',sizeof(buffer));

if(pipe(file_pipes) == 0)
{
fork_result
=fork();
if(fork_result==-1)
{
fprintf(stderr,
"Fork failure");
return 1;
}
if(fork_result==0)
{
data_processed
=read(file_pipes[0],buffer,BUFSIZ);
printf(
"read %d bytes:%s\n",data_processed,buffer);
return 1;
}
else
{
data_processed
=write(file_pipes[1],some_data,strlen(some_data));
printf(
"write %d bytes\n",data_processed);
}
}
return 0;
}

posted @ 2010-10-23 13:47  linyilong  阅读(244)  评论(0编辑  收藏  举报