下面的程序用于不断的启动hello,并将其杀死。将hello换为别的可执行文件即可简单测试程序的健壮性。
#include <stdio.h>
#include <unistd.h>int main(int argc, char* argv[])
{
int i;
int flag;
pid_t pid;
char buf[128] = {0};
printf("argc:%d\n", argc);
if (2 != argc)
{
printf("Usage:./a.out 3\n");
return 0;
}
int total_times = atoi(argv[1]);
for(i = 0; i < total_times; i++)
{
// 如果不指定全路径,则只检查PATH变量中存储的命令
if((pid = fork())==0) {
printf("in child process 1......\n");
//flag = execvp("./hello", NULL);
//envp变量的用
char *envp[]={"PATH=.", NULL};
flag = execve("/usr/local/test/code/hello", NULL, envp);
if(flag == -1)
printf("exec error!\n");
return 0;
}
else
{
printf("pid is:%d\n", pid);
sprintf(buf, "kill -9 %d", pid);
printf("buf is:%s\n", buf);
sleep(1);
system(buf);
}
}
printf("in parent process ......\n");
return 0;
}