歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux教程 >> Linux exec函數的使用

Linux exec函數的使用

日期:2017/2/28 15:53:16   编辑:Linux教程

1. 示例

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

2. hello程序
  1. #include <stdio.h>
  2. int main(void)
  3. {
  4. printf("Hello world!\n");
  5. return 0;
  6. }
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