linux: exec实战

打开一个.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文件输入参数的选择==

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值