Chinaunix首页 | 论坛 | 博客
  • 博客访问: 668720
  • 博文数量: 845
  • 博客积分: 5000
  • 博客等级: 大校
  • 技术积分: 5015
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-15 16:22
文章分类

全部博文(845)

文章存档

2011年(1)

2008年(844)

我的朋友

分类:

2008-10-15 16:25:08

   初识Linux/C语言编程,管道和重定向暨fork与execlp函数的理解

   Linux中C语言的编程有两个环境下根本无须考虑的问题,关于管道和重定向的概念。

    昨晚研究了一个通宵,关于fork()和execlp()函数,基本上用fork函数实现管道,用execlp来实现重定向。不过它们两个实现功能的方法都非常奇怪。

    fork函数是让程序创建一个跟自己一模一样的副本,就跟当下流行的很多网络游戏中副本的概念差不多,昨晚在练习的时候忽然感到,这玩意儿又有点像WEB 编程中的表单自提交。在同一个程序里面写两套方案,运行时让其中的一套(安排在fork>=1的分支结构中)调用来自自身代码文件中的另一套方案 (安排在fork==0分支结构)乍一看这跟管道根本就挨不着边,我一开始也是觉得这样,就像一个进程又去调用了一个进程一样,不过另外调用的进程又是本 身,大脑里一团浆糊一样。那么请看代码吧:

    CODE:

   

 /**//*
============================================================================
Name : fork_example.c
Author : newflypig
Version :
Copyright : Your copyright notice
Description : Hello World in C, Ansi-style
============================================================================
*/

#include
#include
#include
#include
#include
#include

int main(void) ...{
int i=1;
printf("in the begining,the value=%d ",i);
switch(fork())...{
case -1:
fprintf(stderr,"%s ","fork error");
break;
case 0:
printf("child process start,at this time value=%d ",i);
i++;
printf("child process end,at this time value=%d ",i);
break;
default:
printf("parent process: value=%d ",i);
}
return 0;
}

    运行结果是这样的:

    in the begining,the value=1
    child process start,at this time value=1
    child process end,at this time value=2
    parent process: value=1

    可 以看到父进程首先设置i=1然后调用子进程,子进程一开始就有了父进程的i值,然后子进程在自己的基础上将i++了,子进程结束时输出了i=2。当程序返 回父进程时,子进程的改变并没有影响父进程中i的值,i依然为1。这个fork()的功能仅仅如此,有谁会想到让这个函数在Linux最具特色的管道机制 中大显伸手呢。

    花开两朵,各表一枝。

[1]  

【责编:Zenghui】

--------------------next---------------------

阅读(293) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~