1.exec函数
\qquad fork()函数在执行之后,父子进程其实还是执行同一个程序,不同的只是同一个程序的不同分支。如果要想让子进程执行另外一个不同的程序,这时候需要调用exec函数,这时候子进程的用户空间代码和数据完全被新程序替换,从新程序的启动例程开始执行。fork创建新进程,exec并不创建新进程。
2.execlp函数
\qquad 加载一个进程,借助PATH环境变量。
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
int main()
{
pid_t pid;
pid = fork();
if(pid==-1){
perror("fork error");
exit(1);
}
else if(pid==0){
execlp("ls"," ","-l","-h",NULL);
}
return 0;
}
\qquad 运行结果:
-rwxrwxr-x 1 linux linux 16824 11月 21 17:49 exec1
-rw-rw-r-- 1 linux linux 251 11月 21 17:46 exec1.c
-rw-rw-r-- 1 linux linux 375 11月 21 16:10 fork.c
3.execl函数
\qquad 加载一个进程,通过程序名+路径来加载
//加载/usr/bin/ls
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
pid = fork();
if(pid==-1){
perror("fork error");
exit(1);
}
else if(pid==0){
execlp("/usr/bin/ls","a","-l",NULL);
}
return 0;
}
\qquad 还可以加载自己写的程序。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
pid_t pid;
pid = fork();
if(pid==-1){
perror("fork error");
exit(1);
}
else if(pid==0){
execlp("/home/linux/1_CreateProcess/hello"," ddd",NULL);
}
return 0;
}
\qquad
/home/linux/1_CreateProcess/hello
下的可执行程序的c代码程序hello.c
如下:
#include<stdio.h>
int main()
{
printf("hello world!\n");
return 0;
}
4.练习:将当前进程打印到文件中
#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<fcntl.h>
int main()
{
int fd;
fd = open("psout",O_WRONLY|O_CREAT|O_TRUNC,0644);
if(fd<0){
perror("open psout error");
exit(1);
}
dup2(fd,STDOUT_FILENO);
execlp("ps"," ","ax",NULL);
close(fd);
return 0;
}