打开一个.c文件,并编译,如果编译成功,则继续执行这个.c文件。
#include<stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <wait.h>
int main(int argc, char *argv[]){
char filename[512];
if (argc < 2){
fprintf(stderr, "Usage: %s error in input_num\n", argv[0]);
exit(1);
}
strcpy(filename, argv[1]);//文件名
//判断文件类型
char *sub;
if ((sub = strrchr(filename, '.')) == NULL){
fprintf(stderr, "Input file must be .c or .cpp\n");
exit(2);
}
char b_name[512] = {0};//文件名
char f_type[512] = {0};//后缀
strncpy(b_name, filename, sub - filename);
strncpy(f_type, sub, strlen(sub));
printf("%s %s\n", b_name, f_type);
char g_cmd[100] = {0};//编译器名
if (!strcmp(f_type, ".c")){
strcpy(g_cmd, "gcc");
}else if(!strcmp(f_type, ".cpp")){
strcpy(g_cmd, "g++");
}else{
fprintf(stderr, "Usage: %s Input must be .c or .cpp\n", filename);
exit(2);
}
pid_t pid;
if ((pid = fork()) < 0){
perror("fork");
exit(1);
}
if (pid == 0){
//文件名,argv[0], argv[1]...
execlp("vim", "vim", filename, NULL);
}
//不需要判断是不是父进程,因为子进程没有以下代码
wait(NULL);//一定是父进程
if ((pid = fork()) < 0){
perror("fork");
exit(1);
}
if (pid == 0){
execlp(g_cmd, g_cmd, filename, "-o", b_name, NULL);
}
int wstatus;
wait(&wstatus);
if (wstatus == 0){//执行成功返回0吗
printf("exit with %d\n", WIFEXITED(wstatus));//正常返回1
printf("Compile OK!\n");
char temp_name[512] = {0};
sprintf(temp_name, "./%s", b_name);
execv(temp_name, argv + 1);
}else{
printf("Failed!\n");
exit(3);
}
return 0;
}
== 当前并没有对编辑的.c文件输入参数的选择==