//execTest.cpp
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
for(int i = 0; i < argc; i++)
{
cout << " c++ paramater:" << argv[i] << endl;
}
return 3;
}
//shell.sh
#!/bin/bash
for par in "$@"
do
echo " shell parmater : $par"
done
exit 2
//forkTest.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
printf("i am running ...\n");
pid_t id = fork();
if(id == 0) //child
{
printf("child process begin ...\n");
execl("./cppexecTest", "cppexecTest", "1", "2", "3", NULL);
//execl("./shell.sh", "shell.sh", "4", "5", "6", NULL);
sleep(3);
printf("child process end ...\n");
}
//parent process
while(1)
{
int status = 0;
pid_t ret = waitpid(id, &status, WNOHANG); //WNOHANG:不阻塞, 0:阻塞
if(ret > 0)
{
printf("wait child %d success ... exit code %d\n", id, WEXITSTATUS(status));
break;
}
else if(ret == 0)
{
printf("parent process do other things ...\n");
sleep(1);
}
else
{
printf("waitpid error...\n");
break;
}
}
printf("end ... \n");
return 0;
}
分析:
在子进程中打印出 child process begin … 后 使用execl() 函数替换成cppexecTest程序运行,因此子进程不再执行原来的代码,所以子进程不会调用
sleep(3);
printf(“child process end …\n”);
所以看不到 child process end … 打印。
int execl(const char *pathname, const char arg, …/ (char *) NULL */);
int execlp(const char *file, const char arg, …/ (char *) NULL */);
int execle(const char *pathname, const char arg, …/, (char *) NULL, char *const envp[] */);
int execv(const char *pathname, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[], char *const envp[]);
以上的6个函数都是标准C库的函数,它们实际在Linux系统运行时是调用下面这个Linux系统的标准函数
int execve(const char *pathname, char *const argv[], char *const envp[]);
*注:
l(list) 参数地址列表,以空指针结尾
v(vector) 存有各参数地址的指针数组的地址
p(path) 按PATH环境变量指定的目录搜索可执行文件
e(environment) 存有环境变量字符串地址的指针数组的地址