system函数原型
头文件: #include<stdlib.h>
参数:char的指针
返回值:system()函数的返回值如下: 成功,则返回进程的状态值; 当sh不能执行时,返回127; 失败返回-1;
#include <stdlib.h>
int system(const char *command);
//system函数源码
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;
}
源码讲解:当pid=0时进入子进程,else之后的意思父进程等待子进程退出,进入子进程调用exec,执行cmd,所以说system函数是exec族函数封装
根据之前所学exec配合fork的代码可以进行修改
//q3.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int data = 10;
while(1)
{
printf("please inputa data\n");
scanf("%d",&data);
if(data == 1){
pid = fork();
if(pid >0){
wait(NULL);
}
if(pid == 0){
system("./changedata config.txt");
exit(1);
}
}
}
return 0;
}
实验结果

1831

被折叠的 条评论
为什么被折叠?



