进程控制:创建执行其他程序的进程

下面程序创建了一个子进程,子进程使用exec族的函数来执行新的程序,以新的进程代替原有的进程。

#include<sys/types.h>
#include<stdio.h>
#include<unistd.h>
int main(void)
{
		pid_t pid;
		if((pid = fork()) < 0)
		{
				printf("fork error\n");
				exit(1);
		}
		else if(0 == pid)
		{
				printf("Child process PID: %d\n",getpid());
				setenv("PS1","CHILD\\$",1);//设置环境变量
				printf("Process%4d: calling exec.\n",getpid());
				//if(execl("/bin/sh","/bin/sh","arg2",NULL) < 0)
				if(execl("/bin/ls","/bin/ls",NULL) < 0)//调用/bin/ls程序来代替子进程
				{
						printf("Process%4d: execle error!\n",getpid());
						exit(0);
				}
				printf("Process%4d: You should never see this because the chiled is already gone. \n",getpid());
				printf("Precess%4d: The child process is exiting\n");
		}
		else
		{
				printf("Parent process PID:%4d.\n",getpid());
				printf("Process%4d: The parent has fork process %d.\n",getpid(),pid);
				printf("Process%4d: The child has called exec or has exited.\n",getpid());
		}
		return 0;
}

执行结果:


从结果可以看到,子进程执行了ls程序,并且没有打印

You should never see this because the chiled is already gone.
Precess%4d: The child process is exiting
表示子进程已经被新的进程替换。


setenv函数的作用是什么?我们把这条语句注释掉后来看结果:


似乎结果并没有什么变化

那么setenv函数到底是干什么的?

函数原型:

int setenv(const char *name,const char * value,int overwrite);

第一个参数是环境变量名称,第二是参数是值,第三个为1则表示覆盖已有值,为0表示若有已有值则不覆盖。


那可不可以使用execl()函数来调用自己写的程序呢?

我们将程序中的execl语句换成

if(execl("/root/c_p_t/test1","test1:",NULL))
test1是一个打印HelloWorld的小程序

我们看结果:

结论是可以的。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值