linux基础知识——exec函数
生活随笔
收集整理的這篇文章主要介紹了
linux基础知识——exec函数
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.exec函數
\qquadfork()函數在執行之后,父子進程其實還是執行同一個程序,不同的只是同一個程序的不同分支。如果要想讓子進程執行另外一個不同的程序,這時候需要調用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.c3.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; }總結
以上是生活随笔為你收集整理的linux基础知识——exec函数的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: module ‘tensorflow‘
- 下一篇: Linux下Java连接数据库出现 Ac