exec和system的区别 (2)


https://blog.csdn.net/qq_27664167/article/details/82194391

system可以通过返回值的高8位获取脚本的返回值

fork+exec可以根据wait的入口地址形参获取脚本的返回值

其使用上需要注意:

1、 system是阻塞的,wait可以是查询方式的

2、system耗时长,fork+exec+wait耗时短.

编写程序测试。

结果: 

parallels@parallels-Parallels-Virtual-Platform:~/Desktop/LinuxC/System$ ./mySystem 
total time is 1374426 us
total time is 573213 us

测试代码:

#include 
#include 
#include   
#include 
 #include  
 #include 
 #include  


int main()
{

    struct timeval start, end;  // define 2 struct timeval variables

    gettimeofday(&start, NULL); // get the beginning time
    for(int i=0;i<1000;i++)
    {
        char path[256]={0};
        getcwd(path,256); 
        strcat(path,"/mytest");
        int status = system(path);
        //printf("raw return value=%02X,system return value =%d, shell return value=%d \n",status,WIFEXITED(status),WEXITSTATUS(status)); 

        
        getcwd(path,256); 
        strcat(path,"/mytest 102");
        status = system(path);
        //printf("raw return value=%02X,system return value =%d, shell return value=%d \n",status,WIFEXITED(status),WEXITSTATUS(status)); 
}
gettimeofday(&end, NULL);  // get the end time

long long total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
printf("total time is %lld us\n", total_time); 



gettimeofday(&start, NULL); // get the beginning time
 for(int i=0;i<1000;i++)
 {
     pid_t child_pid = fork();
     if(child_pid<0)
     {
         _exit(0);
     }
     else if(child_pid==0)
     {
         char path[256]={0};
        getcwd(path,256); 
        strcat(path,"/mytest");
         execl(path,"mytest", NULL);
         _exit(0);
     }
     else{
         int status;
         wait(&status);
         //printf("status=%x\n",status);
     }


     child_pid = fork();
     if(child_pid<0)
     {
         _exit(0);
     }
     else if(child_pid==0)
     {
         char path[256]={0};
        getcwd(path,256); 
        strcat(path,"/mytest");
         execl(path,"mytest","102", NULL);
         _exit(0);
     }
     else{
         int status;
         wait(&status);
         //printf("status=%x\n",status);
     }
 }

gettimeofday(&end, NULL);  // get the end time

total_time = (end.tv_sec - start.tv_sec) * 1000000 + (end.tv_usec - start.tv_usec); // get the run time by microsecond
printf("total time is %lld us\n", total_time); 

}
#include 
#include 

int main(int argc, char** argv)
{
    if(argc==1)return 100;
    else return atoi(argv[1]);

}