第13章 进程间通信: 管道
进程管道:
popen:
#include <stdio.h>
FILE *fp;
fp = popen("ls -l", "r");
fread = (buff,1,sizeof(buff),fp); //buff 为 字符串变量.
or fp = popen("echo -n","w");
buff[ ] =" hello world"
fwrite = (buff,1,strlen(buff),fp);
pclose(fp);
pipe:
#include <unistd.h>
int pipe(int fildes[2]); //fildes[2] 整型的文件描述符 不是文件流, 所以用 read ,write 操作
//fildes[0]用于读操作, fildes[1]用于写操作, 先进先出
例:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
int pipy[2];
char message[] = "孤灯下的守护者";
char text[32] = "我是一条信息";
pid_t idnum;
int res;
res = pipe(pipy);
if(res == -1)
{
printf("pipe failed\n");
exit(2);
}
idnum = fork();
switch (idnum){
case (-1):
printf("fork failed\n");
exit(1);
case (0):
printf("the text before reading is %s\n",text);
read(pipy[0],text,32);
printf("the text after reading is %s\n",text);
break;
default:
printf("message to write is %s\n",message);
write(pipy[1],message,sizeof(message));
break;
}
exit(0);
}
父进程和子进程: exec