简体   繁体   English

如何从另一个C程序中调用一个C程序

[英]How do you call a C program from within another C program

I have two C programs, Project1A.c and Project1B.c. 我有两个C程序,Project1A.c和Project1B.c。 I'm trying to use execl() to execute Project1A from inside Project1B but so far it's not working. 我正在尝试使用execl()从Project1B内部执行Project1A,但是到目前为止,它无法正常工作。

Project1B.c Project1B.c

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main ()
{
  pid_t pid;

  switch((pid = fork()))
  {
    case -1:
      printf("I'm sorry, fork failed\n");
      break;
    case 0:
      execl("Project1A.c", "./prog", NULL);
      printf("EXECL Unsucessfull");
      break;
    default:
      printf("This is some parent code\n");
      break;
  }
  printf("End of Program\n");

  return 0;
}

execl executes a binary file, meaning you cannot pass it Project1A.c and expect it to work. execl执行一个二进制文件,这意味着您无法将其传递给Project1A.c并期望它能正常工作。 You need to compile it and execute the compile program. 您需要对其进行编译并执行编译程序。

Subsequent arguments to the function are command-line arguments, terminated by NULL. 该函数的后续参数是命令行参数,以NULL终止。 This means that your execl call corresponds to ./Project1A.c ./prog on a shell, which obviously doesn't work. 这意味着您的execl调用对应于外壳程序上的./Project1A.c ./prog,这显然不起作用。

Instead, your execl call should be: execl("prog1A", NULL); 相反,您的execl调用应为: execl("prog1A", NULL); .

On a side not, you could maybe run C code by running the compile command first using the system function and then running the compiled program with execl if the compilation was successful. 另一方面,您可以运行C代码,方法是先使用系统函数运行compile命令,然后如果编译成功,则使用execl运行已编译的程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM