歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux教程

Linux exec函數的使用

1. 示例

  1. /*exec函數示例*/  
  2. #include <stdio.h>   
  3. #include <unistd.h>   
  4.   
  5. int main(void)  
  6. {  
  7.     int flag;  
  8.     pid_t pid;  
  9.     char *const argv[] = {"%U""--user-data-dir=/home/Administrator/.chromiun", NULL};  
  10.     //exec把當前進程印象替換成新的程序文件,故調用進程被覆蓋   
  11.   
  12.     // 如果不指定全路徑,則只檢查PATH變量中存儲的命令   
  13.     if((pid = fork())==0) {  
  14.         printf("in child process 1......\n");  
  15.         //flag = execvp("./hello", NULL);   
  16.         //envp變量的用   
  17.         char *envp[]={"PATH=.", NULL};  
  18.         flag = execve("hello", NULL, envp);  
  19.         if(flag == -1)  
  20.             printf("exec error!\n");  
  21.     }  
  22.   
  23.     if((pid = fork())==0) {  
  24.         printf("in child process 2......\n");  
  25.         //執行ls命令   
  26.         flag = execlp("ls""-al", NULL);  
  27.         if(flag == -1)  
  28.             printf("exec error!\n");  
  29.     }  
  30.       
  31.     if((pid = fork())==0) {  
  32.         printf("in child process 3......\n");  
  33.         //啟動chrome浏覽器   
  34.         flag = execv("/usr/bin/chromium-browser", argv);  
  35.         if(flag == -1)  
  36.             printf("exec error!\n");  
  37.     }  
  38.     printf("in parent process ......\n");  
  39.     return 0;  
  40. }  

2. hello程序
  1. #include <stdio.h>   
  2.   
  3. int main(void)  
  4. {  
  5.     printf("Hello world!\n");  
  6.     return 0;  
  7. }  
3. 運行結果
  1. root@Ubuntu:.../Linux_C/Process# ./exec_t  
  2. in child process 1......  
  3. in parent process ......  
  4. in child process 3......  
  5. root@ubuntu:.../Linux_C/Process# in child process 2......  
  6. Hello world!  
  7. exec_t    fifo_read.c   fork_1.c  hello.c    msg_send.c   signal_1.c  
  8. exec_t.c  fifo_write.c  hello     msg_receive.c  semop_P_V.c  
  9. 已在現有的浏覽器會話中創建新的窗口。  
Copyright © Linux教程網 All Rights Reserved