系统调用fork()和execv函数

7

我正在尝试使用以下C代码依次运行两个可执行文件:

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

int main (int argc, char *argv[])
{
    fork();
    execv("./prcs1", &argv[1]); // GIVE ADDRESS OF 2nd element as starting point to skip source.txt
    fork();
    execv("./prcs2", argv);
    printf("EXECV Failed\n");
}

程序在第一次execv()调用后退出,尽管进行了fork,它从未到达第二个execv()。我已经尝试在第一个fork后调用wait(),但是我不确定缺少什么。有什么想法为什么子进程退出后控制未返回父进程?

啊,老旧的“分叉和执行”习语……不幸的是,它并不像你所说的那么字面化。 - Kerrek SB
1
你想让主进程在执行子进程时阻塞并等待吗? - Kerrek SB
4个回答

24
你需要了解fork和execv如何协同工作
  • fork()克隆当前进程,返回0给子进程,返回childpid给父进程
  • fork()有可能失败,返回-1表示失败,需要判断
  • execv()用新进程替换复制的父进程
  • 典型的fork/exec组合将子进程替换为新进程
  • 通常情况下,你会fork多个子进程,并希望它们同时运行
  • 然而,你要求它们按顺序运行,也就是一个接一个地运行
  • 因此,在启动第二个进程之前,你需要等待第一个进程完成
  • 所以你需要使用某种wait()的变体,下面的示例使用waitpid()等待特定的子进程

你需要stdlib来进行退出处理(以防execv失败),以及errno来输出原因

//I'm trying to run two executables consecutively using this c code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

您可能希望查看您的子进程退出的原因(核心转储、信号、正常退出),因此我添加了这个函数。

#include <sys/types.h>
#include <sys/wait.h>

//WIFEXITED(status) returns true if the child terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().
//WEXITSTATUS(status) returns the exit status of the child.  This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main().  This macro should only be employed if WIFEXITED returned true.
//WIFSIGNALED(status) returns true if the child process was terminated by a signal.
//WTERMSIG(status) returns the number of the signal that caused the child process to terminate.  This macro should only be employed if WIFSIGNALED returned true.
//WCOREDUMP(status) returns true if the child produced a core dump.  This macro should only be employed if WIFSIGNALED returned true.  This macro is not specified in POSIX.1-2001 and is not available on some UNIX implementations (e.g., AIX, SunOS).  Only use this enclosed in #ifdef WCOREDUMP ... #endif.
//WIFSTOPPED(status) returns true if the child process was stopped by delivery of a signal; this is only possible if the call was done using WUNTRACED or when the child is being traced (see ptrace(2)).
//WSTOPSIG(status) returns the number of the signal which caused the child to stop.  This macro should only be employed if WIFSTOPPED returned true.
//WIFCONTINUED(status) (since Linux 2.6.10) returns true if the child process was resumed by delivery of SIGCONT.
int
exitreason(pid_t cid, int status)
{
    if( WIFEXITED(status) )
    {
        printf("child %d terminated normally, that is, by calling exit(3) or _exit(2), or by returning from main().\n",cid);
        if( WEXITSTATUS(status) )
        {
        printf("child %d exit status %d.  This consists of the least significant 8 bits of the status argument that the child specified in a call to exit(3) or _exit(2) or as the argument for a return statement in main().\n",cid,WEXITSTATUS(status));
        }
    }
    if( WIFSIGNALED(status) )
    {
        printf("child %d process was terminated by a signal.\n",cid);
        if( WTERMSIG(status) )
        {
        printf("child %d signal %d that caused the child process to terminate.\n",cid,WTERMSIG(status));
        }
        if( WCOREDUMP(status) )
        {
        printf("child %d produced a core dump.  WCOREDUMP() is not specified in POSIX.1-2001 and is not available on some UNIX implementations (e.g., AIX, SunOS).  Only use this enclosed in #ifdef WCOREDUMP ... #endif.\n",cid);
        }
    }
    if( WIFSTOPPED(status) )
    {
        printf("child %d process was stopped by delivery of a signal; this is only possible if the call was done using WUNTRACED or when the child is being traced (see ptrace(2)).\n",cid);
        if( WSTOPSIG(status) )
        {
        printf("child %d number of the signal which caused the child to stop.\n",cid);
        }
    }
    if( WIFCONTINUED(status) )
    {
        printf("child %d process was resumed by delivery of SIGCONT.\n");
    }
}

这里是您的程序,标注有注释,解释了哪些代码是由父进程处理,哪些是由子进程处理。

int main (int argc, char *argv[])
{
    char proc1[] = "/bin/echo"; //"./prcs1";
    char proc2[] = "/bin/echo"; //"./prcs2";
    pid_t cid1, cid2, cidX;
    int status=0;
    int waitoptions = 0;
    //WNOHANG    return immediately if no child has exited.
    //WUNTRACED  also return if a child has stopped (but not traced via ptrace(2)).  Status for traced children which have stopped is provided even if this option is not specified.
    //WCONTINUED also return if a stopped child has been resumed by delivery of SIGCONT.
    int res;

    if( (cid1 = fork()) == 0 ) //child1
    {
        printf("in child1\n");
        if( (res = execv(proc1, &argv[1])) < 0 ) // GIVE ADDRESS OF 2nd element as starting point to skip source.txt
        {
        printf("error: child1: %d exec failed %d\n", cid1, errno);
        printf("error: cannot execv %s\n",proc1);
        exit(91); //must exit child
        }
    }
    else if( cid1 > 0 ) //cid>0, parent, waitfor child
    {
        cidX = waitpid(cid1, &status, waitoptions);
        printf("child1: %d res %d\n", cid1, res);
        exitreason(cid1, status);
    }
    else //cid1 < 0, error
    {
        printf("error: child1 fork failed\n");
    }

    if( (cid2 = fork()) == 0 ) //child2
    {
        printf("in child2\n");
        if( (res = execv(proc2, &argv[1])) < 0 ) // GIVE ADDRESS OF 2nd element as starting point to skip source.txt
        {
        printf("error: child2: %d exec failed %d\n", cid2, errno);
        printf("error: cannot execv %s\n",proc2);
        exit(92); //must exit child
        }
    }
    else if( cid2 > 0 ) //cid>0, parent, waitfor child
    {
        cidX = waitpid(cid2, &status, waitoptions);
        printf("child2: %d res %d\n", cid2, res);
        exitreason(cid2, status);
    }
    else //cid2 < 0, error
    {
        printf("error: child2 fork failed\n");
    }
}

第三点:你可以说execv()用一个新程序替换了子进程 - Will

20

您有几个问题。首先,如果您只想运行两个程序,只需要调用一次 fork()。然后在父进程中运行一个程序,在子进程中运行另一个程序。其次,您正在不正确地构造要传递给execvargv数组。第一个条目应该是可执行文件的名称。请这样做:

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

int main(int argc, char **argv)
{
    pid_t i = fork();
    if (i == 0)
    {
        execv("./prcs1", (char *[]){ "./prcs1", argv[1], NULL });
        _exit(1);
    }
    else if (i > 0)
    {
        execv("./prcs2", (char *[]){ "./prcs2", argv[0], NULL });
        _exit(2);
    }
    else
    {
        perror("fork failed");
        _exit(3);
    }
}

请注意,此示例未执行错误检查。


还有一个完全不合理的 return 0 :-S - Kerrek SB
是的,只是试图关闭系统。我想如果execv失败了,它应该在那里。 - Carl Norum
任何到达该点的方式都是错误的...但为了安全起见,在子进程的exec之后,我还会添加_exit(EXIT_FAILURE) - Kerrek SB
好的,根据评论进行了改进。 - Carl Norum
2
不想挑剔,但最近由于tcmalloc和pthread_atfork引起的一系列死锁后,我真的坚持在子进程中使用_exit。在fork之后继续下去就非常危险。我想,如果应用程序保证是单线程的(您的分配器是否承诺?您知道吗?),那么也许可以,但为什么要冒险呢。 - Kerrek SB
1
你能保证你的内存分配器没有启动正在持有锁的线程吗? - Kerrek SB

6

我猜您对fork()函数的了解不多。当您调用fork()函数时,它会创建一个子进程,并从fork处运行相同的代码。

fork()函数返回三种值:

  • 负数,表示出现错误
  • 正数,表示您在父进程中,该值为子进程ID
  • 零,表示您在子进程中。

您的代码应该像这样:

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

int main (int argc, char *argv[])
{

    int ret = fork();
    if(ret==0)
    {
       //child process
       execv("./prcs1", &argv[1]); // GIVE ADDRESS OF 2nd element as starting point to skip source.txt
       printf("EXECV Failed from child\n");
    }
    else if(ret>0)
    {
       //parent process
       execv("./prcs2", argv);
       printf("EXECV Failed from parent\n");
    }
    else
    {
       //you will come here only if fork() fails.
       printf("forkFailed\n");
    }
    return 0;
}

+1 表示运行来自分支的相同代码。这很重要,因为代码不是从头开始运行,而是整个数据和堆栈被复制,同时在 Region 表中文本保持不变,但程序计数器的副本会更新。我认为这是最相关的答案。 - Akash

4
< p > exec系列将只在调用失败时返回。

由于您没有检查fork的返回值,因此您将在父进程和子进程中都调用execv

检查返回值:如果它是0,则您在子进程中,如果大于零,则在父进程中。小于零表示fork失败。


实际上,如果execv()成功,它是永远不会返回的。请参见http://linux.die.net/man/3/execv。 - Markku K.
返回失败,但你是对的...我会编辑答案。 - LostBoy

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接