1.system函数
system函数原型:
int system(const char *command); |
system函数相对exec族函数简单粗暴。并且system函数执行完毕后还会从函数调用点继续往下执行代码
返回值:
system()在调用/bin/sh时成功则返回进程状态值
system()在调用/bin/sh时失败则返回-1
其他失败原因(如sh不能执行)返回127
2.使用system函数
示例代码一:
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<string.h>
#include<stdlib.h>
int main()
{
pid_t pid;
int data;
while(1)
{
printf("please input a data\n");
scanf("%d",&data);
if(data == 1)
{
pid = fork();
if(pid > 0)
{
wait(NULL);
}
if(pid == 0)
{
//execl("./changData","changData","config.txt",NULL);
system("changData config.txt");
}
}
else
{
printf("wath,do nothing !\n");
}
}
return 0;
}
运行结果:
示例代码二:
#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");
if(system("ps") == -1)//-1为system调用失败
{
printf("execl failed!\n");
perror("why");//打印错误原因
}
printf("after execl\n");
return 0;
}
运行结果: