Linux的system函数的实现源码
system()会调用fork()产生子进程,由子进程来调用/bin/sh-c cmdstring来执行参数cmdstring字符串所代表的命令,此命令执行完后随即返回原调用的进程。
int system(const char * cmdstring)
{
pid_t pid;
int status;
if(cmdstring == NULL){
return (1);
}
if((pid = fork())<0){
status = -1;
}
else if(pid == 0){
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
-exit(127); //子进程正常执行则不会执行此语句
}
else{
while(waitpid(pid, &status, 0) < 0){
if(errno != EINTER){
status = -1;
break;
}
}
}
return status;
}
system函数的应用一
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int data=10;
while(1){
printf("please input a data\n");
scanf("%d",&data);
if(data==1){
pid=fork();
if(pid>0)
{
wait(NULL);
}
else if(pid==0){
// execl("./changData","chuangData","config.txt",NULL);
system("./changData config.txt");
}
}
else{
printf("wait, do nothing\n");
}
}
return 0;
}
system函数的应用二
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//函数原型:int execl(const char *path, const char *arg, ...);
int main(void)
{
printf("This pro get system date:\n");
/* char *argv[] = {"ps",NULL,NULL};
if(execv("/bin/ps",argv) == -1) */
// if(execlp("ps","ps",NULL,NULL) == -1)
if(system("ps")==-1)
{
printf("execl failed!\n");
perror("why");
}
printf("after execl\n");
return 0;
}
popen函数
比system函数在应用中的好处:可以获取运行的输出结果
#include <stdio.h>
FILE *popen(const char *command, const char *type);
若type是”r”,则文件指针是连接到子进程执行command命令的标准输出,如果type是”w”,则文件指针连接到子进程执行command命令的标准输入。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
int main(void)
{
char ret[1024]={0};
FILE *fp;
fp = popen("ps","r");
int nread = fread(ret,1,1024,fp);
printf("read ret %d byte, ret=%s\n",nread,ret);
return 0;
}