exec函数族(重点俩个,以及个dup2的配合使用)
dup2是文件的重定向(第二个参数重定向到第一个参数)
文件描述符1代表标准输出
文件描述符2代表标准输入
execlp:借助PATH环境变量 (执行系统命令或者函数用这个)
execl:路径加程序名 (用户自定义的可执行程序)
int execl(const char *path, const char *arg, ...)
int execv(const char *path, char *const argv[])
int execle(const char *path, const char *arg, ..., char *const envp[])
int execve(const char *path, char *const argv[], char *const envp[])
int execlp(const char *file, const char *arg, ...)
int execvp(const char *file, char *const argv[])
***execlp 和execv的简单使用
#include<stdio.h>
2 #include <stdlib.h>
3 #include<unistd.h>
4
5 int main()
6 {
7 pid_t pid;
8 pid = fork();
9 if(pid == -1)
10 {
11 perror("fork error");
12 exit(1);
13 }
14 else if( pid > 0 )
15 {
16 sleep(1);
17 printf("I am partent\n");
18 }
19 else
20 //execlp("ls","ls","-l",NULL);
21 //execl("/home/s/main","main",NULL);
22 execlp("ps","ps","aux",NULL);
23 return 0;
代码结果
dup2与exec配合使用
#include<stdio.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
int fd = open("open.out",O_CREAT | O_WRONLY,0777);
if(fd == -1)
{
perror("open error");
exit(1);
}
dup2(fd,STDOUT_FILENO);
execlp("ps","ps","aux",NULL);
return 0;
}