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

C/C++:linux进程通信简单例子(管道)

2014-06-26 17:19 429 查看
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

int main(void)
{
int fd[2],nbytes;
pid_t childpid;
char string[] = "Hello, World!\n";
char readbuffer[80];

pipe(fd);
int w_fd = fd[1];
int r_fd = fd[0];

if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}

if(childpid == 0)
{
close(r_fd);
write(w_fd,string,strlen(string));
printf("Writing string%s ", string);
exit(0);
}
else
{
close(w_fd);
nbytes = read(r_fd, readbuffer,sizeof(readbuffer));
printf("Received string:%s\n",readbuffer);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: