您的位置:首页 > 运维架构 > Linux

[Linux] 由管道父进程向子进程发送数据 (父子间IPC)

2013-12-17 17:38 435 查看
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cstdlib>
#include <unistd.h>

using std::cin;
using std::cout;
using std::endl;
using std::string;
typedef string String;

const int MAXLINE = 1005;

int main() {
int n;
int fd[2];
pid_t pid;
char line[MAXLINE];
cout << "hehe\n";
cout << fd[0] << ' ' << fd[1] << endl;
if (pipe(fd) < 0) {
fprintf(stderr, "iipe error");
}
if ((pid = fork()) < 0) {
fprintf(stderr, "fork error");
}
else if(pid > 0) { // parent
cout << "par : " << fd[0] << ' ' << fd[1] << endl;
close(fd[0]);
write(fd[1], "hello world\n", 12);
}
else {
cout << "son: " << fd[0] << ' ' << fd[1] << endl;
close(fd[1]);
n = read(fd[0], line, MAXLINE);
cout << "n : " << n << endl;
cout << "line : " << line << endl;
write(STDOUT_FILENO, line, n);
}
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: