先上一个自己的测试程序,本来是想试一下execve函数生成子进程。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
extern char **environ;
int main(int argc, char **argv){
pid_t pid = 0;
int ret = 0;
int index =0;
printf("argc is %d \n",argc);
while(NULL != argv[index]){
printf("argv[%d] is %s\n",index,argv[index]);
index++;
}
#if 0
for(index = 0; index < argc; index++){
printf("argv[%d] is %s\n",index,argv[index]);
}
printf("argv[%d] is %s\n",index,argv[index]);
#endif
if((pid = fork()) < 0){
printf("fork error:");
}else if(pid == 0){
index = 0;
while(NULL != environ[index]){
printf("envv[%d] is %s\n",index,environ[index]);
index++;
}
ret = execve("new",argv,environ);
printf("child process %d.\n",ret);
}else{
printf("parent process .\n");
}
return 0;
}
1,argv 和 environ 这两个字符串数组,注意最后必须有NULL作为结束符。 The argv and envp arrays must each include a null pointer at the end of the array.因为有如此特性,所以可以打印argv,而不需要判断argc.
int index =0;
printf("argc is %d \n",argc);
while(NULL != argv[index]){
printf("argv[%d] is %s\n",index,argv[index]);
index++;
}
2,execve 会替换子进程的代码段,所以如果execve执行成功了,后面的printf("child process") 是 永远也不会执行的。