日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > linux >内容正文

linux

linux基础知识——exec函数

發布時間:2024/7/19 linux 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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 1121 17:49 exec1 -rw-rw-r-- 1 linux linux 251 1121 17:46 exec1.c -rw-rw-r-- 1 linux linux 375 1121 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; }

總結

以上是生活随笔為你收集整理的linux基础知识——exec函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。