简体   繁体   English

使用fork和exec在C linux中执行程序

[英]executing a program in C linux using fork and exec

I want to execute a C program in Linux using fork and exec system calls. 我想使用forkexec系统调用在Linux中执行C程序。 I have written a program msg.c and it's working fine. 我已经写了一个程序msg.c ,它工作正常。 Then I wrote a program msg1.c . 然后我编写了一个程序msg1.c。

When I do ./a.out msg.c , it's just printing msg.c as output but not executing my program. 当我执行./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;
}

argv[0] contains your program's name and you are Echo'ing it. argv [0]包含程序的名称,您正在回显它。 Works flawlessly ;-) 完美地工作;-)

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

your exec executes the program echo which prints out whatever argv's value is; 您的执行程序执行程序回显,打印出argv的值;
furthermore you cannot "execute" msg.c if it is a sourcefile, you have to compile ( gcc msg.c -o msg ) it first, and then call something like exec("msg") 此外,如果它是一个源文件,则不能“执行” msg.c,必须先对其进行编译( gcc msg.c -o msg ),然后再调用exec("msg")

C programs are not executables (unless you use an uncommon C interpreter). C程序不是可执行文件 (除非您使用不常用的C解释器)。

You need to compile them first with a compiler like GCC , so compile your msg.c source file into a msg-prog executable (using -Wall to get all warnings and -g to get debugging info from the gcc compiler) with: 您需要先使用GCC之类的编译器对其进行编译,然后使用以下命令将msg.c源文件编译为msg-prog可执行文件(使用-Wall获取所有警告,使用-ggcc编译器获取调试信息):

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

Take care to improve the msg.c till you get no warnings. 小心改进msg.c直到没有任何警告。

Then, you might want to replace your execv in your source code with something more sensible. 然后,您可能想用更明智的方式替换源代码中的execv Read execve(2) and execl(3) and perror(3) . 读取execve(2)execl(3)perror(3) Consider using 考虑使用

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

Read Advanced Linux Programming . 阅读高级Linux编程

NB: You might name your executable just msg instead of msg-prog .... 注意:您可以将可执行文件命名为msg而不是msg-prog ...。

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

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