0

创建从命令行获取 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 程序从两个文件中读取一些输入数据并将数据存储到另一个文件中。

4

2 回答 2

1

This code more or less does what you say your program should do. In particular, it uses argv[2] as the program name. It uses snprintf() to avoid overflows with long arguments (but doesn't verify that it didn't overrun). It prints various status messages — partly as a debugging aid, partly to give meaning to the various parts of the program.

#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;
}

When this file is named gc.c and is compiled to make gc, it can be run as:

$ ./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
$

The usage message from gc2 is correct; the program expects 6 arguments, not the 4 it is given by the program.

于 2013-05-26T02:55:58.040 回答
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;
}
于 2013-05-26T00:11:46.190 回答