进程间内存独立且相互不可见,进程间通信需要特殊方法
匿名管道pipe()
/* Create a one-way communication channel (pipe).
If successful, two file descriptors are stored in PIPEDES;
bytes written on PIPEDES[1] can be read from PIPEDES[0].
Returns 0 if successful, -1 if not. */
extern int pipe (int __pipedes[2]) __THROW __wur;
输入一个2个元素的int数组地址,生成单向匿名管道,调用后该数组[0]为读取描述符,[1]为写入描述符,默认打开,使用前需要关闭另一通道,然后直接调用系统调用函数write open来进行读写
一个实例
#include "sys/wait.h"//waitpid声明处
#include "sys/types.h"//pid_t声明处,实质是int
#include "stdio.h"
#include "unistd.h"//系统调用函数声明 fork,close,write read pipe等
#include "stdlib.h"
#include "string.h"
int main(int argc, char const *argv[])
{
int p[2];
pipe(p);//两个文件描述符已经打开
pid_t cpid = fork();
if(cpid == 0)
{
char buf[11] = {0};
close(p[1]);//关闭写管道
read(p[0], buf, 10); //从读管道中读取一次,最多读取10字节
printf("child process read: %s\n",buf);
printf("child process end\n");
exit(0);//打印出来,退出
}
else if(cpid > 0)
{
close(p[0]);//关闭读管道
char buf2[100] = {0};
scanf("%s", buf2);//从标准输入读取一段数据
write(p[1], buf2, strlen(buf2));//通过管道发送到子进程
waitpid(cpid, NULL, 0);//等待子进程结束
printf("parent process end\n");
}
/* code */
return 0;
}
运行,分别输入10字节以上和10字节以下的数据看看