c - Unix 进程 - 编译和运行 c 程序

标签 c unix process

创建一个从命令行获取 n 个参数 arg1、arg2、...、argn 的父进程。 arg1 是源 C 的名称,arg2 是编译 arg1 后的可执行文件的名称,arg3, ... , argn 是启动参数。

父进程编译arg1并创建可执行文件arg2,然后将其运行到子进程中。

我尝试使用一些示例来解决问题,但我并没有真正理解它们,因此程序无法运行。我真的需要一些帮助...

#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
#include<string.h>

int main(int argc, char* argv[]){
   char com[200];
   int p;
   p=fork();
   strcpy(com,"gcc -o prog.c");
   strcat(com,argv[1]);

   if(p==0){
       if(WEXITSTATUS(system(com))==0)
          execl("./prog.c","./prog.c",argv[3],argv[4],argv[5],NULL);
   }

   wait(0);
   exit(0);

   return 0;
}

我想要使用的 C 程序从两个文件中读取一些输入数据并将数据存储到另一个文件中。

最佳答案

这段代码或多或少做了你所说的你的程序应该做的事情。特别是,它使用 argv[2] 作为程序名称。它使用 snprintf() 来避免长参数溢出(但不验证它是否没有溢出)。它打印各种状态消息——部分作为调试辅助,部分为程序的各个部分赋予意义。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int main(int argc, char* argv[])
{
    int p;

    if (argc != 6)
    {
        fprintf(stderr, "Usage: %s source program file1 file2 file3\n", argv[0]);
        return(1);
    }

    if ((p = fork()) == 0)
    {
        char com[200];
        snprintf(com, sizeof(com), "gcc -o %s %s", argv[2], argv[1]);
        if (system(com) == 0)
        {
            printf("Compilation of %s successful\n", argv[2]);
            fflush(0);
            execl(argv[2], argv[2], argv[3], argv[4], argv[5], (char *)NULL);
            fprintf(stderr, "Failed to execute %s\n", argv[2]);
            return(1);
        }
        fprintf(stderr, "Compilation of %s from %s failed\n", argv[2], argv[1]);
        return(1);
    }

    int status;

    wait(&status);
    printf("Compilation and execution of %s yielded status %d\n",
           argv[2], WEXITSTATUS(status));
    return 0;
}

当这个文件被命名为gc.c并被编译为gc时,它可以运行为:

$ ./gc gc.c ./gc2 gc.c gc.c gc.c
Compilation of ./gc2 successful
Usage: ./gc2 source program file1 file2 file3
Compilation and execution of ./gc2 yielded status 1
$

来自gc2的使用消息是正确的;该程序需要 6 个参数,而不是程序给出的 4 个。

关于c - Unix 进程 - 编译和运行 c 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16755028/

相关文章:

调用系统调用read导致无限循环

C: "write: Broken pipe"错误

c++ - 在 Linux 上使用 G++ 共享库

c# - 重定向输出时 ResGen.exe 卡住

scala - 从 Scala 中杀死一个挂起的进程

c - 尝试将 C 库包含到 Promela 模型中

C 中的 const 和指针

在 C 语言中实现定时器的 Clock() (time.h) 函数在线程中执行时运行速度是原来的两倍

c - 库函数属于进程或任务吗? (并将函数安排为库函数)

android - Runtime.exec() 错误 : hangs without providing a Process object