https://blog.csdn.net/qq_27664167/article/details/82194391
system可以通過(guò)返回值的高8位獲取腳本的返回值
fork+exec可以根據(jù)wait的入口地址形參獲取腳本的返回值
其使用上需要注意:
1、 system是阻塞的,wait可以是查詢方式的
2、system耗時(shí)長(zhǎng),fork+exec+wait耗時(shí)短.
編寫(xiě)程序測(cè)試。
結(jié)果:
parallels@parallels-Parallels-Virtual-Platform:~/Desktop/LinuxC/System$ ./mySystem total time is 1374426 us total time is 573213 us
測(cè)試代碼:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
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 <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
if(argc==1)return 100;
else return atoi(argv[1]);
}
浙公網(wǎng)安備 33010602011771號(hào)