【问题标题】:how to pass command line arguments to a child process after fork()如何在 fork() 之后将命令行参数传递给子进程
【发布时间】:2011-12-13 14:53:00
【问题描述】:

我有以下代码草稿。

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

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

    printf( "usage: %i filename", argc );

    pid_t pID = fork();
    if (pID == 0)                // child
    {
        // Code only executed by child process
        printf("Child PID: %i", pID);

        int file = open("/tmp/rtail", O_CREAT | O_WRONLY);

        //Now we redirect standard output to the file using dup2
        dup2(file,1);

        char tmp[30];
        sprintf(tmp, "cat `tail -f %s`", argv[1]);
    }
    else if (pID < 0)            // failed to fork
    {
        printf("Failed to fork");
        exit(1);
        // Throw exception
    }
    else                                   // parent
    {

    }

    // Code executed by both parent and child.  

    return 0;
}

如何将命令行参数传递给子进程?比如运行./app alch.txt我要

sprintf(tmp, "cat `tail -f %s`", argv[1]);

生产

cat `tail -f alch.txt`

在 tmp 中。

【问题讨论】:

  • 一模一样?你的代码很好。你到底遇到了什么问题?

标签: c linux operating-system system-calls


【解决方案1】:

如何将命令行参数传递给子进程?

你不需要做任何特别的事情; fork 确保每个进程获取所有局部变量,包括argv

【讨论】:

    【解决方案2】:

    抱歉,它确实工作正常。我的早期版本由于某种原因无法正常工作,但显然我已经更改了一些内容以使其正确。下次提问前会运行我的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-08
      • 2012-09-01
      • 1970-01-01
      • 2020-09-30
      • 1970-01-01
      • 1970-01-01
      • 2013-10-11
      • 2014-07-22
      相关资源
      最近更新 更多