在linux中使用execv而不是execl

时间:2015-02-03 23:11:13

标签: c linux execv execl

我编写了一个使用execl的程序,我希望使用相同的功能,而是使用execv。

这是来自execl的程序:

    #include <stdio.h>
#include <unistd.h>

int main (int argc, char *argv[])
{
  int pid, status,waitPid, childPid;

     pid = fork (); / Duplicate /
     if (pid == 0 && pid != -1) / Branch based on return value from fork () /
     {
       childPid = getpid();
       printf ("(The Child)\nProcess ID: %d, Parent process ID: %d, Process Group ID: %d\n",childPid,getppid (),getgid ());
       execl("/bin/cat","cat","-b","-t","-v",argv[1],(char*)NULL);
   }
     else
   {
     printf ("(The Parent)\nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %d\n",getpid (),getppid (),getgid ());
     waitPid = wait(childPid,&status,0); / Wait for PID 0 (child) to finish . /
   }
   return 1; 
}

然后我尝试修改它,以便使用execv代替,但我无法让它工作(因为它会说没有找到这样的文件或目录)

使用./ProgramName testfile.txt

调用该程序

这是我在execv上的尝试:

#include <stdio.h>
#include <unistd.h>

int main ()
{
  int pid, status,waitPid, childPid;
  char *cmd_str = "cat/bin";
  char *argv[] = {cmd_str, "cat","-b","-t","-v", NULL };
     pid = fork (); / Duplicate /
     if (pid == 0 && pid != -1) / Branch based on return value from fork () /
     {
       childPid = getpid();
       printf ("(The Child)\nProcess ID: %d, Parent process ID: %d, Process Group ID: %d\n",childPid,getppid (),getgid ());
       execv(cmd_str,argv);
   }
     else
   {
     printf ("(The Parent)\nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %d\n",getpid (),getppid (),getgid ());
     waitPid = wait(childPid,&status,0); / Wait for PID 0 (child) to finish . /
   }
   return 1; 
}

任何帮助都会很大,现在已经坚持了很长一段时间。谢谢!

1 个答案:

答案 0 :(得分:4)

您在代码中有一些错误,我将其标记为:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char *argv[])     // <-- missing argc/argv
{
    int pid, status,waitPid, childPid;
    char *cmd_str = "/bin/cat";      // <-- copy/pasta error
    char *args[] = { "cat", "-b", "-t", "-v", argv[1], NULL }; // <-- renamed to args and added argv[1]
    pid = fork (); // Duplicate /
    if (pid == 0) // Branch based on return value from fork () /
    {
        childPid = getpid();
        printf ("(The Child)\nProcess ID: %d, Parent process ID: %d, Process Group ID: %d\n",childPid,getppid (),getgid ());
        execv(cmd_str,args);         // <-- renamed to args
    }
    else
    {
        printf ("(The Parent)\nProcess ID: %d, The Parent Process ID: %d, Process Group ID: %d\n",getpid (),getppid (),getgid ());
        waitPid = wait(childPid,&status,0); // Wait for PID 0 (child) to finish . /
    }
    return 1; 
}