|
利用管道进行进程的通信示例
这里用到了 pipe 管道函数: int pipe(int file_descriptor[2]); 函数 pipe 填充的两个整数的含义是两个文件描述符,任何向 file_descriptor[1] 写入的数据,可以从 file_descriptor[0] 中读取,并且写入的数据符合先入先出的规则. 例 pipe.c: #include #include #include #include
int main() { int data_processed; int file_pipes[2]; const char some_data[]="123"; char buffer[BUFSIZ 1]; int fork_result;
memset(buffer,'\\0',sizeof(buffer));
if(pipe(file_pipes)==0){ fork_result=fork(); /* 设置进程 */ if (fork_result==-1){ /* 判断设置进程是否出错 */ fprintf(serr,"Fork failure"); exit(EXIT_FAILURE); }
/* 下面判断,若是是子进程则读管道数据,父进程则向管道写数据 */
if(fork_result==0){ /* 判断是否子进程 */ data_processed=read(file_pipes[0],buffer,BUFSIZ); /* 从管道读数据 */ printf("Read %d bytes:%s\n",data_processed,buffer); exit(EXIT_SUCCESS); } else { /* 父进程 */ data_processed=write(file_pipes[1],some_data,slen(some_data)); /* 向管道写数据 */ printf("Wrote %d bytes\n",data_processed); } } exit(EXIT_SUCCESS); }
程序运行:./pipe 执行结果: Wrote 3 bytes Read 3 bytes:123 利用管道进行通信成功!^o^
来源:十度教育 作者: 关键字:利用管道进行进程,通信示例 发表日期:2006-6-24 20:28:59 网页显示有限 阅读全文请下载本文完整版WORD文档
上一篇:C语言时钟源程序(按机械表行走和按电子表显示时间和日期) 下一篇:一个简单的打字练习程序
2008-11-23 21:24:56
|