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:[email protected] > 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:[email protected] > 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; }
运行程序:
[[email protected] popen]$ gcc popen.c -o main [[email protected] popen]$ gcc reverse.c -o reverse [[email protected] popen]$ ./main ./reverse how are you you are how baby u r beautiful beautiful r u baby [[email protected] popen]$
按 ctrl+D 退出popen.c中的循环,从而退出程序。
时间: 2024-10-05 21:14:33