系统调用fork()和execv函数 [英] System Call fork() and execv function

查看:969
本文介绍了系统调用fork()和execv函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行两个可执行文件连续使用这个C code:

I'm trying to run two executables consecutively using this c code:

#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()调用后退出程序,而不会继续第二execv()。我试过调用wait()的第一个叉后,但我不知道这是它缺少什么。

The program exits after the first execv() call despite the fork, it never gets to the second execv(). I've tried calling wait() after the first fork but I'm not sure that's what it's missing.

任何想法,为什么控制不孩子退出后返回到父?

Any ideas why control doesn't return to the parent after the child exits?

推荐答案

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

You have a couple of problems. First, if you only want to run two programs, you only need to call fork() once. Then run one program in the parent process and one in the child. Second, you're constructing the argv array to be passed to execv incorrectly. The first entry should be the executable name. Do something like:

#include <stdio.h>
#include <unistd.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);
    }
}

请注意,这个例子没有错误检查。

Note that this example does no error checking.

这篇关于系统调用fork()和execv函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆