标准管道(popen),标准管道popen
标准管道(popen),标准管道popen
NAME popen, pclose - pipe stream to or from a process SYNOPSIS #include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream); DESCRIPTION The popen() function opens a process by creating a pipe, forking, and invoking the shell. Since a pipe is by definition unidirectional, the type argument may specify only reading or writing, not both; the resulting stream is correspondingly read-only or write-only. The command argument is a pointer to a null-terminated string contain- ing a shell command line. This command is passed to /bin/sh using the -c flag; interpretation, if any, is performed by the shell. RETURN VALUE The popen() function returns NULL if the fork(2) or pipe(2) calls fail, or if it cannot allocate memory. The pclose() function returns -1 if wait4(2) returns an error, or some other error is detected.
写
popen.c,如下:
/************************************************************************* > File Name: popen.c > Author: KrisChou > Mail:zhoujx0219@163.com > Created Time: Fri 22 Aug 2014 11:07:26 AM CST ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char buf[1024]; FILE *fp; while(memset(buf,0,1024),fgets(buf,1024,stdin) != NULL) { fp = popen(argv[1],"w"); fputs(buf,fp); pclose(fp); } return 0; }
被调用函数reverse.c,如下:
/************************************************************************* > File Name: reverse.c > Author: KrisChou > Mail:zhoujx0219@163.com > Created Time: Sat 23 Aug 2014 11:21:27 AM CST ************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char *argv[]) { char word[256]; //从标准输入读取字符串 char buf[256][256],index = 0; //保存从标准输入读取的字符串 while(memset(word,0,256), scanf("%s",word) != EOF ) { strcpy(buf[index++],word); } index--; while(index >=0 ) { printf("%s ",buf[index]); index--; } printf("\n"); return 0; }
运行程序:
[purple@localhost popen]$ gcc popen.c -o main [purple@localhost popen]$ gcc reverse.c -o reverse [purple@localhost popen]$ ./main ./reverse how are you you are how baby u r beautiful beautiful r u baby [purple@localhost popen]$
按 ctrl+D 退出popen.c中的循环,从而退出程序。
这个函数的功能应该是读取当前目录下的内容的
popen可以启动一个新的进程,ls -l则是要启动进程得程序名和参数,ls -l当然即使列出目录的意思咯
"r"是代表调用进程可以通过返回的文件指针读取到新启动的进程的输出。也可以是"w",这样调用进程就可以通过向文件写内容而新启动的进程从标准输入读取。事实上这就是进程间的管道通信。
popen返回一个文件指针,返回空指针也就是0即出错咯。
下面的while循环,就是把返回的文件的内容读取到传入的sck文件描述符所指向的文件中,fileno是把文件指针转换为文件描述符
pclose函数就是关闭这个管道,它的返回值是新启动的这个程序的退出码,
一般来说程序都返回0代表正确嘛,非零当然就表示程序可能有问题,如果是pclose函数错误会返回-1
全部信息
高级会员信息
最新信息
同时有188人正在找"管道标识国家标准"信息,发布此类信息,让客户主动找到你!
出售电厂锅炉专用管道
新旧程度:不限供货总量:多吨型号规格:不限交易价格:电议或面议所在地区:内蒙古存放方式:不限
本公司发布的其它供求信息 点此查看更多赤峰宇恒商贸有限公司
联系人:徐先生 | 所在地:内蒙古
评论暂时关闭