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. 已在现有的浏览器会话中创建新的窗口。  

相关内容