Linux exec函数的使用

28 篇文章 1 订阅

1. 示例

/*exec函数示例*/
#include <stdio.h>
#include <unistd.h>

int main(void)
{
	int flag;
	pid_t pid;
	char *const argv[] = {"%U", "--user-data-dir=/home/Administrator/.chromiun", NULL};
	//exec把当前进程印象替换成新的程序文件,故调用进程被覆盖

	// 如果不指定全路径,则只检查PATH变量中存储的命令
	if((pid = fork())==0) {
		printf("in child process 1......\n");
		//flag = execvp("./hello", NULL);
		//envp变量的用
		char *envp[]={"PATH=.", NULL};
		flag = execve("hello", NULL, envp);
		if(flag == -1)
			printf("exec error!\n");
	}

	if((pid = fork())==0) {
		printf("in child process 2......\n");
		//执行ls命令
		flag = execlp("ls", "-al", NULL);
		if(flag == -1)
			printf("exec error!\n");
	}
	
	if((pid = fork())==0) {
		printf("in child process 3......\n");
		//启动chrome浏览器
		flag = execv("/usr/bin/chromium-browser", argv);
		if(flag == -1)
			printf("exec error!\n");
	}
	printf("in parent process ......\n");
	return 0;
}


2. hello程序

#include <stdio.h>

int main(void)
{
	printf("Hello world!\n");
	return 0;
}

3. 运行结果

root@ubuntu:.../Linux_C/Process# ./exec_t
in child process 1......
in parent process ......
in child process 3......
root@ubuntu:.../Linux_C/Process# in child process 2......
Hello world!
exec_t	  fifo_read.c	fork_1.c  hello.c	 msg_send.c   signal_1.c
exec_t.c  fifo_write.c	hello	  msg_receive.c  semop_P_V.c
已在现有的浏览器会话中创建新的窗口。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值