【操作系统】fork()、exec()函数学习笔记

fork()函数可以创建一个新的进程,该进程是父进程的拷贝,称为子进程。

exec()函数可以在当前进程中执行一个新的函数。

fork()函数的例子如下:

#include<stdio.h>
#include<unistd.h>

/*
*说明:         本例参考了ALP
*函数名:       main
*函数功能:     通过fork()函数创建进程,并获得子进程和父进程的进程号
*修改时间:     2013年5月3日
*/
int main()
{
        pid_t child_pid;        //进程的数据类型为pid_t
        child_pid=fork();       //调用fork()函数创建新进程
        /*进入父进程*/
        if(child_pid!=0){
                printf("the process ID is %d\n",getpid());      //获得当前进程号
                printf("the child process IS is %d\n",child_pid);       //子进程
号
        }
        /*进入子进程*/
        else{
                printf("the process ID is %d\n",getppid());     //获得父进程号
                printf("the child process ID is %d\n",getpid());        //当前进
程号
        }
        return 0;
}


fork()函数一次调用,两次返回,并且每次调用该函数返回的进程号都不相同,结果如下:



相关的函数说明如下:

函数名:fork()
头文件:<unistd.h>
函数原型:pid_t fork(void)
函数功能:创建新进程
返回值:父进程返回子进程号,子进程返回0,否则返回-1

函数名:getpid()、getppid
头文件:<unistd.h>
函数原型:pid_t getpid(void)、pid_t getppid(void)
函数功能:获取当前进程号、获取父进程号

exec()函数实现了一个进程调用另外一个函数的功能,关于execl()相关的几个函数区别见点击打开链接

例子如下:

例子:

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>

/*
*说明:		本例参考了《Linux C编程一站式学习》
*函数名:	main
*功能:		利用dup2()函数实现了重定向,exec()函数的调用
*修改日期:	2013年5月2日
*/

int main(int argc,char *argv[])
{
	int fd;
	/*判断命令行参数的个数*/
	if(argc!=2){
		fputs("usage:wrapper file\n",stderr);	//错误信息输出到标准错误文件
		exit(1);	//非正常退出
	}
	fd=open(argv[1],O_RDONLY);	//只读方式打开文件,返回文件描述符
	/*出错时返回-1*/
	if(fd<0){
		perror("open");		//将错误信息输出到标准错误文件
		exit(1);
	}
	dup2(fd,STDIN_FILENO);		//复制文件描述符
	close(fd);
	execl("./upper","upper",NULL);	//调用upper执行另一程序
	perror("exec ./upper");		//只有出错才有返回
	exit(1);
}

其中upper.c的代码如下,其实现了将小写字母转换成大写字母:

#include<stdio.h>
#include<ctype.h>	//toupper的头文件
int main(void)
{
	int ch;
	while((ch=getchar())!=EOF)
		putchar(toupper(ch));	//小写字母转换成大写字母
	return 0;
}	

运行以上程序有:


相关的几个函数说明如下:

函数名:dup2()
头文件:<unistd.h>
函数功能:实现文件描述符的复制
参数说明:oldfd--旧的文件描述符         newfd--新的文件描述符
返回值:成功返回文件描述符,否则返回-1

函数名:execl()
头文件:<unistd.h>
函数原型:int execl(const char *path,const char *arg)
函数功能:将当前进程切换到另外一个函数(调用功能)
参数说明:path--执行路径         arg--有效的程序调用列表
返回值:成功不返回,失败返回-1

函数名:open
头文件:<fcntl.h>
函数原型:int open(const char *pathname,int flags)
函数功能:打开文件
参数说明:path--文件名          flags--打开文件的方式
返回值:成功返回文件描述符,否则返回-1


如有问题,请联系zjgsuffddybz@gmail.com



  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值