Linux---system函数
Linux线程system函数的简单运用。
·
一、关于system函数
#include <stdlib.h>
int system(const char *command);
返回值:成功,返回进程的状态值;当sh不能运行时,返回127;失败,返回-1。
源代码如下:
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;
}
通过源代码涉及三个函数:fork()函数、waitpid()函数、以及execl函数。因此,只有这三个函数全部顺利运行才可以实现system函数。
实现步骤为:判断输入的字符串是否为空,随后调用fork函数创建子进程,通过子进程调用shell脚本对cmd字符串中的文件进行实现。
system函数的运用:
//待修改文件
LENG =0 //待修改数据初始值
HIGH =8
SPEED =9
HIGH =2
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int fdSrc;
char *readBuf = NULL;
fdSrc = open("./config.txt",O_RDWR);
int size = lseek(fdSrc,0,SEEK_END);
readBuf = (char*)malloc(sizeof(char)*size);
lseek(fdSrc,0,SEEK_SET);
read(fdSrc,readBuf,size);
char* p = strstr(readBuf,"LENG =");
if(p == NULL){
printf("found error\n");
exit(-1);
}
p = p+strlen("LENG =");
*p = '8';
lseek(fdSrc,0,SEEK_SET);
write(fdSrc,readBuf,strlen(readBuf));
printf("change success\n");
close(fdSrc);
return 0;
}
使用system函数进行调用:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int status;
int num;
pid_t pid;
while(1){
printf("Please insert the num\n");
scanf("%d",&num);
if(num == 1){
pid = fork();
if(pid < 0){
perror("fork\n");
}
if(pid == 0){
printf("before system\n");
if((status = system("./changedata")) == -1){
perror("system\n");
}
printf("after system\n");
exit(0);
}else if(pid > 0){
wait(NULL);
}
}else{
printf("no wait\n");
}
}
return 0;
结果:
system函数的优点:
1、由于system函数的实现调用了shell命令进行,因此在传参时无需指定路径,shell会根据当前环境变量下寻找到该可执行程序。
2、使用system而不是直接使用fork和exec的优点是:system进行所需的各种出错处理以及各种信号处理。
3、与exec族函数不相同的是:system函数调用可执行文件后不会覆盖原程序。而是在调用处继续执行。
更多推荐
已为社区贡献2条内容
所有评论(0)