UNIX fork()以及管道pipe()
2019年4月10日
fork()函数会将函数后面的代码执行复制一遍,由此产生父子进程,这个函数对父进程返回子进程的id号,对子进程返回0,对前面的代码只执行一遍,用fork函数创建的是无名管道,同时,还可以创建又名管道,但是本人没有用过,用pipe函数可以创建一个半双工,用于进程间传输大量数据。通过
write
函数写数据,通过
read
函数读数据。下面是示例代码。
#include <iostream> #include <unistd.h> #include <string> #include <stdlib.h> std::string father = "message from father\n"; std::string child = "message from child\n";
int main(){ int chan1[2]; int chan2[2]; char buff[50];
pipe(chan1); pipe(chan2);
if(fork()){
close(chan1[0]);
close(chan2[1]);
write(chan1[1],father.c_str(),father.length());
close(chan1[1]); read(chan2[0],buff,50); close(chan2[0]); std::cout<<buff; }else{
close(chan1[1]);
close(chan2[0]);
write(chan2[1],child.c_str(),child.length());
close(chan2[1]);
read(chan1[0],buff,50);
close(chan1[0]);
std::cout<<buff;
}
return 0; }
在管道中chan1[1]以及chan2[1]表示写管道,chan1[0],chan2[0]表示读管道,对于不用的要及时关闭。
上面代码的输出是
GeSHi Error: GeSHi could not find the language tx (using path /home/wwwroot/default/wp-content/plugins/codecolorer/lib/geshi/) (code 2)
Previous
boost库实现UDP通信
Newer