exec函数族
- fork子进程后,父子进程使用的是同一代码,要想子进程执行父进程以外的代码,就需要调用exec函数族来实现.
- execlp()
1>该函数通常用来调用系统程序:ls;date;cp…
2>实现
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include <unistd.h>
#include<stdlib.h>
int main()
{
printf("*****************\n");
int pid;
pid=(int)fork();
if(pid==-1)
{
perror("fork error:");
exit(1);//#include<stdlib.h>
}
else if(pid>0)
{
sleep(1);
}
else{
/*******************************************************
*函数:execlp() //l:list;p:PATH
*头文件:#include <unistd.h>
*格式:int execlp(const char *file, const char *arg, ..../* (char *) NULL *//*)*/;//变参函数.const char *file:可执行文件名;const char *arg:跟多个参数;最后以NULL(哨兵)结尾.
/*作用:fork子进程后,父子进程使用的是同一代码,要想子进程执行父进程以外的代码,就需要调用exec函数族来实现.该函数通常用来调用系统程序:ls;date;cp....
*返回值:The exec() functions return only if an error has occurred. The return value is -1, and errno is set to indicate the error.
********************************************************/
//子进程实现将当前系统的进程信息输出到文件test_env.text里.
int fd=open("test_env.text",O_RDWR|O_CREAT|O_TRUNC,774);
dup2(fd,1);//将stdin重定向到fd,就会输出到test_env.text,而不是屏幕.
execlp("ps","ps","aux",NULL); //第二个ls是因为ls程序里没有使用argv[0]这个参数,但是必须要占位,不能不写.
//判断exec函数族执行结果写法,不用写if.
perror("execlp");//错误才返回,成功不会返回,所以此处不用写if.
exit(1);
}
printf("****************\n");
return 0;
}
- execl()
1>该函数通常用来调用指定路径下的可执行程序(比如自己写的).
2>代码实现
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
printf("*****************\n");
int pid;
pid=(int)fork();
if(pid==-1)
{
perror("fork error:");
exit(1);//#include<stdlib.h>
}
else if(pid>0)
{
sleep(1);
}
else{
/*******************************************************
*函数:execl()
*头文件:#include <unistd.h>
*格式: int execl(const char *path, const char *arg, .../* (char *) NULL *///);//变参函数:const char *path:可执行文件路径;const char *arg:跟多个参数(注意:第一个参数没有作用,但是必须有);最后以NULL(哨兵)结尾.
/*作用:fork子进程后,父子进程使用的是同一代码,要想子进程执行父进程以外的代码,就需要调用exec函数族来实现.该函数通常用来调用指定路径下的可执行程序(比如自己写的).
*返回值:The exec() functions return only if an error has occurred. The return value is -1, and errno is set to indicate the error.
********************************************************/
execl("../include/app1","app1",NULL); //第二个ls是因为ls程序里没有使用argv[0]这个参数,但是必须要占位,不能不写.
}
printf("****************\n");
return 0;
}