Linux exec函数的使用

1. 示例

/*exec函数示例*/
#include 
#include 

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 

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


你可能感兴趣的:(C/C++,Linux)