Linux的exec族函数使用示例


1. 示例

[cpp]  view plain copy
  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. }  

整理函数直接可使用为如下:


static int CreateSubProcessAndExecv(const char* executableFile_,
		char* const argvs[] )
{
	//char *const argv[] = {"%U", "--user-data-dir=/home/Administrator/.chromiun", NULL};
    pid_t pid;
    if((pid = fork()) == -1) {
        printf("Error in fork\n!\n!\n!\n");
        exit(1);
    }
    if(pid == 0) {
        printf("spawning sub process \n");
        execv(executableFile_,
        		argvs);
        exit(0);
    }
    return pid ;
}



2. hello程序

[cpp]  view plain copy
  1. #include <stdio.h>  
  2.   
  3. int main(void)  
  4. {  
  5.     printf("Hello world!\n");  
  6.     return 0;  
  7. }  

3. 运行结果

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



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值