【问题标题】:executing a program in C linux using fork and exec使用 fork 和 exec 在 C linux 中执行程序
【发布时间】:2014-03-14 10:50:21
【问题描述】:

我想使用forkexec 系统调用在Linux 中执行一个C 程序。 我写了一个程序 msg.c 并且运行良好。然后我写了一个程序msg1.c

当我执行./a.out msg.c 时,它只是将msg.c 打印为输出,但不执行我的程序。

#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(int argc,char** argv)
{
/*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;
}

【问题讨论】:

  • 你希望 /bin/echo 做什么?
  • 我不知道。写什么?我试图理解它。

标签: c linux fork system-calls


【解决方案1】:

argv[0] 包含您的程序名称,您正在回显它。 完美运行 ;-)

【讨论】:

    【解决方案2】:

    /bin/echo msg.c 将打印 msg.c 作为输出,如果您需要执行 msg 二进制文件,那么您需要将代码更改为 execv("path/msg");

    【讨论】:

      【解决方案3】:

      您的 exec 执行程序 echo,它打印出 argv 的值;
      此外,如果它是源文件,则不能“执行” msg.c,您必须先编译(gcc msg.c -o msg)它,然后调用类似exec("msg")

      【讨论】:

      • 谢谢。但是你能不能解释一下,因为我是第一次这样做。
      【解决方案4】:

      C 程序不是executables(除非您使用不常见的 C 解释器)。

      您需要先使用compiler 编译它们,例如GCC,因此将您的msg.c 源文件编译为msg-prog 可执行文件(使用-Wall 获取所有警告,使用-g 获取调试信息来自gcc 编译器)与:

      gcc -Wall -g msg.c -o msg-prog
      

      注意改进msg.c,直到你没有收到任何警告。

      然后,您可能希望将源代码中的execv 替换为更合理的内容。阅读execve(2)execl(3)perror(3)。考虑使用

      execl ("./msg-prog", "msg-prog", "Foo is my name", NULL);
      perror ("execl failed");
      exit (127);
      

      阅读Advanced Linux Programming

      注意:您可以将可执行文件命名为 msg 而不是 msg-prog ....

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-12-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-06-09
        相关资源
        最近更新 更多