2013-05-26 45 views
0

创建一个父进程,它从命令行获得n个参数arg1,arg2,...,argn。 arg1是源C的名称,arg2是来自编译arg1的可执行文件结果的名称,而arg3,...,argn是要启动的参数。Unix进程 - 编译并运行c程序

父代编译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程序我想使用,读取两个文件和存储数据的一些输入数据到另一个文件。

+2

“该程序不能正常工作”不是一个问题... – Dave

+0

你真的不得不问一个问题。 –

+0

看看你的第二个'strcat'的结果,你会发现它的格式不正确。此外,您尝试执行C程序而不是编译输出。 –

回答

0

您应该查看exec的手册,该手册将告诉您如何运行exec以分叉根据规范行事的另一个进程。此代码可以帮助你如何在变量传递给一个子进程:

#include <stdio.h> 
#include <stdlib.h> 
#include <unistd.h> /* for fork */ 
#include <sys/types.h> /* for pid_t */ 
#include <sys/wait.h> /* for wait */ 

int main() 
{ 
    /*Spawn a child to run the program.*/ 
    pid_t pid=fork(); 
    if (pid==0) { /* child process */ 
     static char *argv[]={"echo","Foo is my name.",NULL}; 
     execv("/bin/echo",argv); 
     exit(127); /* only if execv fails */ 
    } 
    else { /* pid!=0; parent process */ 
     waitpid(pid,0,0); /* wait for child to exit */ 
    } 
    return 0; 
} 
1

此代码或多或少没有你说什么你的程序应该做的。特别是,它使用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个参数。